gpt4 book ai didi

javascript - 从 Checkbox/ListItem 获取 onCheck 值

转载 作者:行者123 更新时间:2023-12-01 02:17:19 26 4
gpt4 key购买 nike

假设我有以下由实现 material-ui 组件的 React.Component 呈现的内容:

{data.map(value => (
<ListItem
key={data.indexOf(value)}
primaryText={value}
leftCheckbox={
<Checkbox
onCheck={this.props.handleAddOption}>
</Checkbox>}>
</ListItem>

当选择复选框时,我想将值插入状态的数组

handleAddOption = (value) => {

this.setState((....))

}

我该如何去做呢?

更新在这里找到了解决方案Passing a function with parameters through props on reactjs

最佳答案

您需要将值从 CheckBox 组件传递到函数 prop。您可以通过以下方式执行此操作:

<ListItem
key={data.indexOf(value)}
primaryText={value}
leftCheckbox={
<Checkbox
onCheck={(e, isChecked) => this.props.handleAddOption(value, isChecked)}>
</Checkbox>}>
</ListItem>

对于你的处理程序:

handleAddOption(value, isChecked) {
this.setState((prevState, props) => {
// Get the old state's value, sticking with immutable pattern
let yourProperty = prevState.yourProperty;
// Determine if the value already exists in your property's array
const exists = yourProperty.find(v => v === value);

if (isChecked) {
// If the checkbox is checked...
// If the property exists, don't do anything
// If it isn't there, add it
!exists && yourProperty.push(value);
} else {
// If the checkbox is NOT checked...
// If the property exists, filter the array to remove it
// If it isn't there, do nothing
exists && (yourProperty = yourProperty.filter(v => v !== value));
}

// Return the new state
return { yourProperty };
});
}

更新我用文档和几个拼写错误更新了解决方案,并在此处的 CodeSandBox 上创建了一个工作示例:https://codesandbox.io/s/pj0m4w3qp7

关于javascript - 从 Checkbox/ListItem 获取 onCheck 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49416800/

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