3 回答
TA贡献1831条经验 获得超4个赞
请查看此完整示例。基本上,您在单击处理程序上设置状态时遇到了问题。
selectItemClickHandler = () => {
this.setState({
listItems: [{itemOptionSelector: [{isSelected: true}]}]
})
}
selectItemClickHandler 的更新代码应为:
selectItemClickHandler = (event, index) => {
this.setState(prevState => {
const list = [];
prevState.listItems.map((item, i) => {
if (i === index) {
item.itemOptionSelector.map(selector => {
selector.isSelected = true
})
}
list.push(item);
});
return {
listItems: list
};
});
};
以下是我更改上述代码的完整示例
import React, {Component} from 'react'
export default class ListExample extends Component {
constructor(props) {
super(props);
this.state = {
listItems: [
{
name: 'firstItem',
itemOptionSelector: [
{id: 1,isSelected: false},
{id: 2,isSelected: false},
{id: 3,isSelected: false},
]
},
{
name: 'secondItem',
itemOptionSelector: [
{id: 1,isSelected: false},
{id: 2,isSelected: false},
{id: 3,isSelected: false},
]
}
]
}
}
selectItemClickHandler = (event, index) => {
this.setState(prevState => {
const list = [];
prevState.listItems.map((item, i) => {
if (i === index) {
item.itemOptionSelector.map(selector => {
selector.isSelected = true
})
}
list.push(item);
});
return {
listItems: list
};
});
};
render() {
const {listItems} = this.state;
return (
<div>
{listItems.map((item, index) => {
return <div key={index} className="button" onClick={(event) => {
this.selectItemClickHandler(event, index)
}}>{item.name}</div>
})}
<button onClick={()=>{ console.log(this.state, 'current state') }}>Show State in Console</button>
</div>
)
}
}
TA贡献1880条经验 获得超4个赞
首先,不清楚你想做什么。您没有呈现“子项”(或选项),因此当前无法知道应将哪个选项更改为所选状态。
通常,您可以像这样更新数组状态:
state = {
items: [
{ isSelected: false, name: 'first' },
{ isSelected: false, name: 'second' },
{ isSelected: false, name: 'third' },
]
};
// ...
handleItemClick = (item, index) => {
const items = this.state.items.slice();
items[index] = { ...item, isSelected: !item.isSelected };
this.setState({ items });
};
render() {
return this.state.items.map((item, index) =>
<div onClick={() => this.handleItemClick(item, index)}>{item.name}</div>);
}
TA贡献1839条经验 获得超15个赞
我将发布一个示例,因为不清楚您要更新的内容。
假设这是您的状态。
state = {
items: [
{
id: 1,
isSelected: false,
},
{
id: 2,
isSelected: false,
},
{
id: 3,
isSelected: false,
}
]
};
这就是你如何渲染你的项目。
<ul>
{this.state.items.map((item, index) => (
<li key={item.id} onClick={this.handleToggle(index)}>
{item.id} {item.isSelected + ""}
</li>
))}
</ul>
然后,您的处理程序需要如下所示。
// pay attention to the handler which creates a closure
handleToggle = index => () => {
const items = [...this.state.items];
items[index].isSelected = !items[index].isSelected;
this.setState({ items });
};
添加回答
举报