gpt4 book ai didi

javascript - 使用 React 实现多个列表的拖放

转载 作者:行者123 更新时间:2023-11-28 05:28:05 25 4
gpt4 key购买 nike

我正在尝试通过 React 实现多个列表的拖放,但我似乎无法让它工作!

我的颜色对象在放置后发生变化,但它没有将项目放置在准确的位置。此外,在拖动时,占位符在 ul 有效放置区之外也可见。

var colors = {
"a": ["Red", "Green", "Blue"],
"b": ["Yellow", "Black", "White", "Orange"]
};
var placeholder = document.createElement("li");
placeholder.className = "placeholder";
var List = React.createClass({
getInitialState: function() {
return {
data: this.props.data
};
},
dragStart: function(key, index, e) {
this.dragged = e.currentTarget;
this.contentToBeDragged_src = e.currentTarget.parentNode;
e.dataTransfer.effectAllowed = 'move';
// Firefox requires dataTransfer data to be set
e.dataTransfer.setData("text/html", e.currentTarget);
},
dragEnd: function(key, index, e) {
console.log(key + ' ' + index);
this.dragged.style.display = "block";
//this.dragged.parentNode.removeChild(placeholder);
// Update data
var data = this.state.data;
var from = Number(this.dragged.dataset.id);
var to = Number(this.over.dataset.id);
data[index].splice(0, data[index].splice(from, 1)[0]);
this.setState({
data: data
});
},
dragOver: function(e) {
e.preventDefault();
//this.dragged.style.display = "none";
if (e.target.className == "placeholder") return;
this.over = e.target;
// Inside the dragOver method
var relY = e.clientY - this.over.offsetTop;
var height = this.over.offsetHeight / 2;
var parent = e.target.parentNode;
if (relY > height) {
this.nodePlacement = "after";
parent.insertBefore(placeholder, e.target.nextElementSibling);
} else if (relY < height) {
this.nodePlacement = "before"
parent.insertBefore(placeholder, e.target);
}
},
render: function() {
var context = this;
var lists = Object.keys(context.state.data).map(function(key) {
return <ul onDragOver = {
context.dragOver
} > {
context.state.data[key].map(function(item, i) {
return ( <
li data - id = {
i
}
key = {
i
}
draggable = "true"
onDragEnd = {
(evt) => context.dragEnd(key, i, evt)
}
onDragStart = {
(evt) => context.dragStart(key, i, evt)
} >
{
item
} <
/li>
)
}, context)
} <
/ul>
});

return <div > {
lists
} < /div>

}
});

ReactDOM.render( <
List data = {
colors
}
/>, document.getElementById('app')
);

这是我尝试的一个jsfiddle。 jsfiddle

任何帮助将不胜感激,谢谢!

最佳答案

至于放置部分,问题出在您编写的dragEnd()中:

data[index].splice(0, data[index].splice(from, 1)[0]);

第一个问题是当您应该使用data[key]时却使用了data[index](您不需要索引)。第二个问题是你的移动操作,它可能不会达到你的预期。该行应该如下所示:

data[key].splice(to, 0, data[key].splice(from, 1)[0]);

关于javascript - 使用 React 实现多个列表的拖放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39962053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com