gpt4 book ai didi

javascript - 如何在 ReactJS 中使用单击事件从列表中删除项目?

转载 作者:数据小太阳 更新时间:2023-10-29 04:10:26 24 4
gpt4 key购买 nike

var FilterList = React.createClass({
remove: function(item){

this.props.items = this.props.items.filter(function(itm){
return item.id !== itm.id;
});

return false;
},
render: function() {
var createItem = function(item) {
return (
<li>
<span>{item}</span>
<a href data-id="{item.id}" class="remove-filter" onClick={this.remove.bind(item)}>remove</a>
</li>

);
};
return <ul>{this.props.items.map(createItem.bind(this))}</ul>;
}
});
var FilterApp = React.createClass({
getInitialState: function() {
return {items: [], item: {
id: 0,
type: null
}};
},
onChangeType: function(e){
this.setState({
item: {
id: this.state.items[this.state.items.length],
type: e.target.value
}
});
},
handleSubmit: function(e) {
e.preventDefault();
var nextItems = this.state.items.concat([this.state.item]);
var item = {};
this.setState({items: nextItems, item: {}});
},
render: function() {
return (
<div>
<h3>Filters</h3>
<FilterList items={this.state.items} />

<form className="filter" onSubmit={this.handleSubmit}>
<fieldset>
<legend>Filter</legend>
<div className="form-grp">
<select name="type" onChange={this.onChangeType}>
<option>foo</option>
<option>bar</option>
<option>baz</option>
</select>
</div>
</fieldset>
<div className="actions">
<button>{'Add #' + (this.state.items.length + 1)}</button>
</div>
</form>
</div>
);
}
});

React.render(<FilterApp />, document.body);

我似乎无法思考如何从列表中删除项目。可能在这里也做出了很多其他糟糕的设计决定,新手。

最佳答案

组件上的 Props 是不可变的,这意味着您不能直接修改它们。在上面的示例中,如果 FilterList 组件想要删除一个项目,它需要从父组件调用回调。

一个简化的example of this .

FilterApp 将删除函数传递给在 onClick 事件上调用的 FilterList。这将从父项中删除一个项目,更新状态,然后导致 FilterList 使用新内容重新呈现。

希望这对您有所帮助。

关于javascript - 如何在 ReactJS 中使用单击事件从列表中删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27817241/

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