gpt4 book ai didi

javascript - 如何在reactjs中过滤组件/元素数组

转载 作者:行者123 更新时间:2023-11-28 13:12:23 25 4
gpt4 key购买 nike

这样我就可以在点击按钮时通过事件获取按钮。但是当我进行过滤时,它不会删除所述按钮。

所以我在构造函数()中有我的数组:

constructor()
{
super();
this.options = [ 1, 2, 3, 4, 5];
this.temp_option = [];
this.delete_me = this.delete_me.bind(this);
this.buttons = [<button key="0" onClick={this.delete_me}/>,<button key="1" onClick={this.delete_me}/>];
this.state = { buttons: this.buttons };
}

然后我有这个功能:

delete_me(e)
{
console.log(e.target);
this.buttons = this.buttons.filter((item) => item != e.target);
console.log(this.buttons);
}

但是 this.buttons 中仍然有两个元素。

我想到了另一种删除它的方法,那就是使用“ key ”,但我似乎找不到任何有关获取 key 值的信息。

最佳答案

您当前采取的方法并不是真正的“ react ”。你需要更多地考虑状态的改变,而不是直接改变 dom。

一种方法是:

class App extends React.Component {
constructor(){
super();
this.state ={
visibleButtons: [ 11, 22, 33, 44 ],
buttons: {
11: {
label: "Foo",
},
22: {
label: "Bar"
},
33: {
label: "Cow",
},
44: {
label: "Pig"
},
},
}
}

onDelete(deletedId) {
this.setState({
visibleButtons: this.state.visibleButtons.filter(id => id !== deletedId)
});
}

render () {
return (
<div>
{ this.state.visibleButtons.map(buttonId => (
<button key={buttonId} onClick={() => this.onDelete(buttonId)}>{this.state.buttons[buttonId].label}</button>
)) }
</div>
);
}
}

ReactDOM.render(<App/>,document.getElementById('root'));

http://codepen.io/cjke/pen/RKwWwZ?editors=0010

<小时/>

编辑

显示添加和删除的示例。唯一的 id 非常原始,并且不会主动检查其中的内容,但您应该了解要点:

class App extends React.Component {
constructor(){
super();
this.onAdd = this.onAdd.bind(this);
this.onChange = this.onChange.bind(this);

this.state ={
value: '',
uniqueId: 100,
visibleButtons: [ 11, 22, 33, 44 ],
buttons: {
11: {
label: "Foo",
},
22: {
label: "Bar"
},
33: {
label: "Cow",
},
44: {
label: "Pig"
},
},
}
}

onDelete(deletedId) {
this.setState({
visibleButtons: this.state.visibleButtons.filter(id => id !== deletedId)
});
}

onChange(e) {
this.setState({ value: e.target.value });
}

onAdd(e) {
this.setState({
uniqueId: this.state.uniqueId + 1,
value: '',
buttons: {
...this.state.buttons,
[this.state.uniqueId]: {
label: this.state.value,
}
},
visibleButtons: [...this.state.visibleButtons, this.state.uniqueId],
});
}

render () {
return (
<div>
<div>
{ this.state.visibleButtons.map(buttonId => (
<button key={buttonId} onClick={() => this.onDelete(buttonId)}>{this.state.buttons[buttonId].label}</button>
)) }
</div>
<br/>
<div>
<input onChange={this.onChange} value={this.state.value}/><button onClick={this.onAdd}>+</button>
</div>
</div>
);
}
}

ReactDOM.render(<App/>,document.getElementById('root'));

关于javascript - 如何在reactjs中过滤组件/元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41436251/

25 4 0
文章推荐: javascript - DojoToolkit widget.placeAt() 方法引用
文章推荐: javascript - 找不到用于排序/更改
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com