这个问题是关于https://github.com/clauderic/react-sortable-hoc .
我对 React 还很陌生,所以我发现以下内容有点烦人。去
https://jsfiddle.net/7tb7jkz5/ .通知第 4 行
const SortableItem = SortableElement(({value}) => <li className="SortableItem" onClick={console.debug(value)}>{value}</li>);
运行代码时,控制台会将“Item 0”记录到“Item 99”。单击一个项目将记录相同的日志,但 三 次。为什么会发生这种情况?这真的是必要的还是更像是一个错误?
我期望一个类似于普通 DOM 的行为,所以点击事件会从被点击的项目中冒泡出来,并且可以通过其祖先被捕获。观察到的行为在我看来就像单击事件会被列表发送到每个列表项三遍。
更新:
嗯,这实际上就像 Crystal 一样清晰,谢谢你指出这一点,舒巴姆。我不仅指定了一个引用,而且还指定了对 console.debug 的实际调用,每次计算表达式时都会执行该调用。常见的错误。
尽管如此,这意味着,当我单击其中一个时,每个列表项都会呈现(我猜)三次。我怀疑缺少优化甚至无用的重绘。
最佳答案
您可以使用 react-sortable-hoc 定义和处理单击事件的另一种方法:
请检查下面的代码
import { SortableContainer, SortableElement, arrayMove } from 'react-sortable-hoc';
const SortableItem = SortableElement(({ value }) => {
return (
<div >
<div id="button_value">{value}</div>
</div >
);
});
const SortableList = SortableContainer(({ items }) => {
return (
<div >
{items.map((value, index) => (
<SortableItem
key={`item-${index}`}
index={index}
value={value}
/>
))}
</div>
);
});
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
};
}
onSortEnd = ({ oldIndex, newIndex }) => {
this.setState(({ items }) => ({
items: arrayMove(items, oldIndex, newIndex),
}));
};
shouldCancelStart = (e) => {
var targetEle = e;
if (!targetEle.id) {
targetEle = e.target;
}
if (targetEle.id === 'button_value') {
console.log('Div button click here ');
// perform you click opration here
}
// you can define multiple click event here using seprate uniq id of html element even you can manage delay on click here also using set timeout and sortmove props and sortend props you need to manage just one boolean flag.
}
render() {
return (
<div>
<SortableList
items={this.state.items}
onSortEnd={this.onSortEnd}
onSortStart={(_, event) => event.preventDefault()}
shouldCancelStart={this.shouldCancelStart} />
</div>
);
}
}
export default App;
首先在 html 元素中定义 id button_value ,然后使用这个 id 你可以使用这个 props shouldCancelStart 获得点击事件
关于reactjs - react-sortable-hoc : Handling of click event on list item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40784874/