从Checkbox / ListItem

时间:2018-03-21 21:26:40

标签: javascript html reactjs material-ui

我们说React.Component实施material-ui组件后,我有以下内容:

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

选择Checkbox后,我想将值推送到state

中的数组中
handleAddOption = (value) => {

    this.setState((....))

}

我该怎么做?

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

1 个答案:

答案 0 :(得分:2)

您需要将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