gpt4 book ai didi

reactjs - 如何从reactjs列表中删除点击时的li元素?

转载 作者:行者123 更新时间:2023-12-03 14:15:08 24 4
gpt4 key购买 nike

    var ListItem = require('./listItem');

var App = React.createClass({
getInitialState : function(){
return{
items : []
}
},

deleteElement: function(){
},

addElement : function(){
this.state.items.push(<ListItem />);
this.forceUpdate();
},

render : function(){
return (
<div>
<ul>{this.state.items.map(function(item,i){return (
<li>
<p onClick='this.deleteElement'>(-)</p>
{item}
</li>
)})}</ul>
<p onClick='this.addElement'>(+)</p>
</div>
);
}
});

Currently I can add li elements to the array using addElement function.But can't figure out how to remove the particular li element from the ul list on clicking the deleteElement function.I tried using splice() but didn't work.I am new to reactjs.So don't know how to remove the li elements on click in the react way.

最佳答案

您的代码中有几个错误

  1. 不要使用this.forceUpdate();,而应该使用setState

  2. onClick 您应该传递对函数的引用而不是字符串'this.addElement'

现在考虑如何从列表中删除元素。,您需要传递到 deleteElement 索引 this.deleteElement.bind(this, i) 并按索引删除元素items 数组,然后设置新状态

var App = React.createClass({
getInitialState : function(){
return {
items : []
}
},

deleteElement: function(index) {
this.setState({
items: this.state.items.filter(function (e, i) {
return i !== index;
})
});
},

addElement: function() {
this.setState({
items: this.state.items.concat(<ListItem time={ +new Date() } />)
});
},

render: function() {
var list = this.state.items.map(function(item, i) {
return <li key={ i }>
<p onClick={ this.deleteElement.bind(this, i) }>(-)</p>
<span>{ item }</span>
</li>
}, this);

return <div>
<ul>{ list }</ul>
<p onClick={ this.addElement }>(+)</p>
</div>
}
});

Example

关于reactjs - 如何从reactjs列表中删除点击时的li元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35338961/

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