Van*_*vig 0 javascript arrays reactjs react-state
我有为多个项目呈现的多个按钮。所有按钮都有一个我传递给键的唯一 ID,我试图根据唯一 ID 禁用该按钮。禁用布尔值处于状态,当单击按钮时,我希望它禁用那个唯一的按钮。
但是,我的代码禁用了所有呈现的按钮。
我已经使用 map 来访问我所在州的 park items 数组,因此如果我将它们转换为具有该州唯一键的数组,我不确定如何映射按钮。
这是我到目前为止所拥有的:
我的状态:
this.state = {
parks: [],
todos: [],
disabled: false
};
Run Code Online (Sandbox Code Playgroud)
按钮:
<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
})
}
>
Run Code Online (Sandbox Code Playgroud)
您可以通过将disabled状态放入包含items' id 的数组来实现它。
然后在 line 中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"))Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1599 次 |
| 最近记录: |