我已尝试构建一个具有拖放列表功能的react应用程序,而无需下载任何外部软件包。我发现a tutorial确实是这样做的
这是我的代码:
class App extends React.Component {
state = {
items: ["3", "2", "1", "4"]
};
onDragStart = (e, index) => {
console.log("drag start!!!");
this.draggedItem = this.state.items[index];
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/html", e.target.parentNode);
e.dataTransfer.setDragImage(e.target.parentNode, 20, 20);
};
onDragOver = index => {
const draggedOverItem = this.state.items[index];
// if the item is dragged over itself, ignore
if (this.draggedItem === draggedOverItem) {
return;
}
// filter out the currently dragged item
let items = this.state.items.filter(item => item !== this.draggedItem);
// add the dragged item after the dragged over item
items.splice(index, 0, this.draggedItem);
this.setState({ items });
};
onDragEnd = () => {
this.draggedIdx = null;
};
render() {
return (
<div className="App">
<main>
<h3>List of items</h3>
<ul>
{this.state.items.map((item, idx) => (
<li key={item} onDragOver={() => this.onDragOver(idx)}>
<div
className="drag"
draggable
onDragStart={e => this.onDragStart(e, idx)}
onDragEnd={this.onDragEnd}
style={{ cursor: "pointer" }}
/>
<span className="content" style={{ cursor: "pointer" }}>
{item}
</span>
</li>
))}
</ul>
</main>
</div>
);
}
}
我在控制台中没有任何错误。但是,列表中的项目拒绝被拖动。偶然的机会,我可以拖动一个项目,但无法将它拖到想要去的地方,它会引入奇怪的间隙/空间: