[英]I'm having trouble getting the ID of an element with a drag-and-drop API
So I'm building my first React app that takes an array and renders its elements onto a page with their own id, I like the use of drag and drop for how the project will end up, but when I drag one of the items to the area I don't seem to be getting the id and I've hit a brick wall after googling for hours.所以我正在构建我的第一个 React 应用程序,它接受一个数组并将其元素渲染到具有自己 id 的页面上,我喜欢使用拖放来确定项目的最终结果,但是当我将其中一个项目拖到我似乎没有得到 ID 的区域,我在谷歌搜索了几个小时后撞到了一堵砖墙。 Here's the function that does the bulk of the work:
这是完成大部分工作的函数:
class Board extends React.Component {
constructor(props){
super(props)
this.state = {field: []}
}
search(stuff) {
//stuff.preventDefault();
for (let i = 0; i < knightDeck.length; i++) {
if (stuff == knightDeck[i].props.name) {
this.setState({ field: [...this.state.field, knightDeck[i]]})
break;
}
}
}
graveyard(stuff) {
stuff.preventDefault();
let data = stuff.dataTransfer.getData("Text")
alert(data.toString())
}
startDrag(e){
e.preventDefault()
e.dataTransfer.setData("Text", e.target.id);
}
render() {
return (
<form
onSubmit={e => {e.preventDefault(); this.search(document.getElementById("draw").value)}}>
<input
type="text"
id="draw"
name="x"
></input>
<button
type="button"
onClick={() => this.search(document.getElementById("draw").value)}>
Enter
</button>
<ol className="list">{this.state.field.map(function(card, index){return <li onDragStart={e => this.startDrag(e)} draggable id={index}>{card}</li>})}</ol>
<div className="delete" onDragOver={(e) => {e.preventDefault()}}onDrop={e => this.graveyard(e)}>Graveyard</div>
</form>
);
}
}
So the area of concern (the dropzone) is graveyard, for now I just have it display the id in an alert dialog box to make sure I get it in the first place and it keeps coming up blank.所以关注的区域(dropzone)是墓地,现在我只是让它在警报对话框中显示id,以确保我首先得到它并且它一直是空白的。 I've used a few things short of jQuery because I'm not sure how that works with react, I know I'm missing something here, any help would be appreciated!
我使用了一些缺少 jQuery 的东西,因为我不确定它如何与 react 一起使用,我知道我在这里遗漏了一些东西,任何帮助将不胜感激! (also I know it's a bit sloppy right now, once I get it working properly I'll clean it up and rename a few things)
(我也知道它现在有点马虎,一旦我让它正常工作,我会清理它并重命名一些东西)
Is it actually dragging?真的是拖吗? I'm not sure if you should have the
e.preventDefault()
in your startDrag function.我不确定您是否应该在 startDrag 函数中使用
e.preventDefault()
。 Remove it and see what happens.删除它,看看会发生什么。
Solved it, this snippet needed fixing, I believe this far deep the this
binding didn't work quite right and came out undefined解决了它,这个片段需要修复,我相信
this
绑定太深了, this
绑定不能正常工作并且未定义
onDragStart={e => this.startDrag(e)}
here's the solution:这是解决方案:
onDragStart={e => {e.dataTransfer.setData("Text", e.target.id)}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.