将函数中的函数传递给函数 [英] pass index from function to function in react
本文介绍了将函数中的函数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个项目列表,点击删除按钮后该项目将被删除。我知道这样做的步骤,但我仍然坚持如何将密钥传递给dlt_item范围。
I have a list of item, and upon on click of the delete button the item will get removed. I know the steps to do it but I'm stuck on how can I pass the key to the dlt_item scope.
http://jsfiddle.net/3Ley7uac/1/
var App = React.createClass({
getInitialState(){
return {
items:[1,2,3]
}
},
dlt_item(key){
//how to get index/id here?
},
renderItem(){
return this.state.items.map((item,i)=> <li key={i}>{item}
<button>Edit</button>
<button onClick={this.dlt_item}>Delete</button>
</li>
)
},
render(){
return(
<ul>
{this.renderItem()}
</ul>
)
}
})
推荐答案
您需要将 this.dlt_item
绑定为
<button onClick={this.dlt_item.bind(this, i)}>Delete</button>
在您的 dlt_item
函数中,您可以拼接传递此索引的状态数组。
and in your dlt_item
function you can splice your state array from this index passed.
代码
var App = React.createClass({
getInitialState(){
return {
items:[1,2,3]
}
},
dlt_item(key){
console.log(key);
this.state.items.splice(key, 1);
this.setState({items: this.state.items});
//how to get index/id here and do setState
},
renderItem(){
return this.state.items.map((item,i)=> <li key={i}>{item}
<button>Edit</button>
<button onClick={this.dlt_item.bind(this, i)}>Delete</button>
</li>
)
},
render(){
return(
<ul>
{this.renderItem()}
</ul>
)
}
})
React.render(<App />, document.getElementById('container'));
JSFIDDLE
您可以使用过滤器
而不是拼接as
Instead of splice you can use filter
as
dlt_item(key){
var items = this.state.items.filter(function(obj){
return obj != (key + 1);
});
console.log(items);
this.setState({items: items});
//how to get index/id here and do setState
},
JSFIDDLE
这篇关于将函数中的函数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文