此示例使用Reactjs和Dexie.js.我有一个没有D的CRUD应用程序,我目前需要它。虽然您可以输入新项目并将其存储到数据库中,但我不确定如何选择已添加的每个项目并将其删除。我知道您必须通过他们的ID选择它们。
使用i标记我附加了.onClick={this.removal}
。但是,我不确定要添加到removal
函数的内容。
var datastored = new Dexie('MyPlace');
datastored.version(1).stores({entries:'++id, title, entry' });
datastored.open().catch(function(err){alert("Could not open database:"+err)});
var Dashboard = React.createClass({
getInitialState:function(){
return {results: [] }
},
runcheck:function(){
let arr = [];
datastored.entries
.each((uploaded)=>arr.push(uploaded))
.then(()=>this.setState({results:arr}));
},
componentDidMount:function(){
this.runcheck();
},
removal:function(){
datastored.entries.delete();
},
sendthru:function(){
var newInput = {
title: this.inputTitle.value,
entry: this.inputEntry.value
};
datastored.entries.add(newInput).then(()=>this.runcheck());
this.inputTitle.value = '';
this.inputEntry.value = '';
},
renderdem:function(){
var list = this.state.results.map(result =>{
return <tr key={result.id}>
<td>{result.id}</td>
<td>{result.title}</td>
<td>{result.entry}
<i className="fa fa-times-circle exout" aria-hidden="true" onClick={this.removal}></i>
</td>
</tr>
});
return (<div>
<p>Title</p>
<input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} />
<p>Entry</p>
<textarea id="inputentry" ref={el => this.inputEntry = el} className="form-control"></textarea>
<button className="btn btn-info" onClick={this.sendthru}>Add</button>
<table className="table table-bordered"><tbody>{list}</tbody></table>
</div>);
},
render:function(){
return this.renderdem();}
});
ReactDOM.render(<Dashboard />, document.getElementById('main'));
我已将我的代码包含在JSFiddle
中答案 0 :(得分:1)
正如您所注意到的,您需要传递id才能知道要删除的内容。但是,在将removal
功能绑定到onClick
时,您无法立即删除该条目。这里的诀窍是让removal
返回一个在点击发生时将被调用的函数。
removal:function(id){
var component = this;
return function(evt) {
datastored.entries.delete(id);
component.runcheck();
}
}
像这样使用:
<i className="fa fa-times-circle exout" aria-hidden="true" onClick={this.removal(result.id)}></i>