gpt4 book ai didi

javascript - 在 React 中根据唯一键禁用按钮?

转载 作者:行者123 更新时间:2023-11-28 17:10:16 25 4
gpt4 key购买 nike

我有多个为多个项目呈现的按钮。所有按钮都有一个我传递给该键的唯一 ID,并且我尝试根据该唯一 ID 禁用该按钮。禁用 bool 值处于状态,当单击按钮时,我希望它禁用该唯一按钮。

但是,我的代码禁用了所有呈现的按钮。

我已经使用 map 来访问我所在州的公园项目数组,因此,如果我将按钮转换为具有该州唯一键的数组,我不确定如何映射按钮。

这是我到目前为止所拥有的:

我的状态:

this.state = {
parks: [],
todos: [],
disabled: false
};

按钮:

<button
key={item.id} //this id is coming from the mapped array "parks" state
disabled={this.state.disabled}
onClick={() =>
this.setState({
todos: [...this.state.todos, item.name], //this adds the parks
//state items to the todos
//state array
disabled: true
})
}
>

最佳答案

您可以通过将 disabled 状态放入包含 items' id 的数组中来实现此目的。

然后在 disabled={this.state.disabled.indexOf(item.id)!==-1} 行中,它检查当前按钮是否存在于 disabled 数组,如果要搜索的值从未出现,.indexOf 方法将返回 -1。

class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
parks: [
{id: 'a', name: "Learn JavaScript" },
{ id: 'b',name: "Learn React" },
{ id: 'c',name: "Play around in JSFiddle"},
{id: 'd', name: "Build something awesome" }
],
todos: [],
disabled: [],
}
}

render() {console.log('todos', this.state.todos)
return (
<div>
<h2>Todos:</h2>
{this.state.parks.map(item => (
<button
key={item.id} //this id is coming from the mapped array "parks" state
disabled={this.state.disabled.indexOf(item.id)!==-1}
onClick={() =>
this.setState({
todos: [...this.state.todos, item.name],
disabled: [...this.state.disabled, item.id]
})
}
>
{item.name}
</button>
))}

</div>
)
}
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

关于javascript - 在 React 中根据唯一键禁用按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54613037/

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