朋友们,我正在ReactJs中编写一个拖放项目示例。我正在将这些项目放入一个新的div中,将它们放入一个新阵列中。现在我的新数组(drop array)应该验证不要在我的新div中删除相同的项目twise。我没有得到如何使用现有的drop数组验证新的拖动项目。
这是我的代码:
<!doctype html>
<html00 lang="en">
<head>
<meta charset="UTF-8">
<title>React JS Example 1</title>
<style>
#div1 {width:350px;height:200px;padding:20px;border:1px solid #aaaaaa;}
</style>
</head>
<body>
<div id="container"></div>
<div id="container1"></div>
<script src="react.js"></script>
<script src="react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
<script type="text/babel">
/*** @jsx React.DOM */
var Employee = React.createClass({
getInitialState: function(){
return {data: [], empName: '',dropData:[]};
},
onClick: function(event){
this.state.data.push({empName: this.state.empName});
this.setState({empName: ''});
},
onNameChange: function(event){
this.setState({empName : event.target.value});
},
drag: function(event) {
event.dataTransfer.setData("div", event.target.id);
},
render: function(){
return(
<div>
<h1> Add New Employees </h1>
Employee Name : <input type="text" value={this.state.empName} onChange={this.onNameChange}/>
<button onClick={this.onClick}>Add</button>
<ul>
{this.state.data.map(function(item, i) {
return (<li data-id={i} id={i} draggable="true" onDragStart={this.drag}>{item.empName}</li>)
}, this)}
{this.state.data.length > 0 ?<NewEmployee data={this.state.data}/> : null}
</ul>
</div>
)
}
});
var NewEmployee = React.createClass({
getInitialState: function(){
return {data: this.props.data,dropData:[]};
},
allowDrop: function(event) {
event.preventDefault();
},
dropItem: function(event) {
event.preventDefault();
var new_data = event.dataTransfer.getData("div"),
arr = this.state.dropData;
arr.push(this.props.data[new_item]);
this.setState({dropData: arr});
},
render: function(){
return(
<div id="div1" onDrop={this.dropItem} onDragOver={this.allowDrop}>
{this.state.dropData.map(function(items, i) {
return (<li>{items.empName}</li>)
}, this)}
</div>
)
}
});
ReactDOM.render(<Employee/>, document.getElementById('container'));
</script>
</body>
</html>
答案 0 :(得分:0)
var NewEmployee = React.createClass({
getInitialState: function(){
return {data: this.props.data,dropData:[]};
},
allowDrop: function(event) {
event.preventDefault();
},
dropItem: function(event) {
event.preventDefault();
var new_data = event.dataTransfer.getData("div"),
arr = this.state.dropData;
if(arr.indexOf(new_data) > -1) {
arr = arr.slice();
arr.push(this.props.data[new_data]);
this.setState({dropData: arr});
}
},
render: function(){
return(
<div id="div1" onDrop={this.dropItem} onDragOver={this.allowDrop}>
{this.state.dropData.map(function(items, i) {
return (<li>{items.empName}</li>)
}, this)}
</div>
)
}
});