如何处理复选框数组上的状态?

时间:2018-12-10 19:01:40

标签: javascript reactjs ecmascript-6

是否可以处理复选框数组的选中状态?

我有这个数组:

const CheckboxItems = t => [
  {
    checked: true,
    value: 'itemsCancelled',
    id: 'checkBoxItemsCancelled',
    labelText: t('cancellations.checkBoxItemsCancelled'),
  },
  {
    checked: true,
    value: 'requestDate',
    id: 'checkboxRequestDate',
    labelText: t('cancellations.checkboxRequestDate'),
  },
  {
    checked: true,
    value: 'status',
    id: 'checkboxStatus',
    labelText: t('cancellations.checkboxStatus'),
  },
  {
    checked: true,
    value: 'requestedBy',
    id: 'checkboxRequestedBy',
    labelText: t('cancellations.checkboxRequestedBy'),
  },
];

我在这里使用它:

class TableToolbarComp extends React.Component {
    state = {
        isChecked: true,
    };

    onChange = (value, id, event) => {       
      this.setState(({ isChecked }) => ({ isChecked: !isChecked }));
    };


    render() {
      const { isChecked } = this.state;
      return (
        {CheckboxItems(t).map(item => (
          <ToolbarOption key={item.id}>
            <Checkbox
              id={item.id}
              labelText={item.labelText}
              value={item.value}
              checked={isChecked}
              onChange={this.onChange}
            />
          </ToolbarOption>
        ))}

      )
    }
}

我遇到的问题是,每当我取消选中某个项目时,其余的项目也会被取消选中。我需要单独管理状态,以通过redux动作将信息发送到其他组件。

编辑:

This is the UI library I am using

1 个答案:

答案 0 :(得分:5)

您将容器的 isChecked用作所有复选框的状态,并在容器上使用一种方法来翻转该标志,使其适用于所有复选框({ {1}}。

相反,要么:

  1. 给出复选框本身的状态,而不是使它们成为简单的对象,或者

  2. 在由复选框项(或可能是其名称)作为键的容器中维护状态图

我倾向于#1,我认为在该库中看起来像这样:

isChecked

更改:

  • 致电class TableToolbarComp extends React.Component { state = { items: CheckboxItems(t) // Your code seems to have a global called `t` }; onChange = (value, id, event) => { this.setState(({ items }) => { // Copy the array items = items.slice(); // Find the matching item const item = items.find(i => i.id === id); if (item) { // Update its flag and set state item.checked = !item.checked; return { items }; } }); }; render() { const { items } = this.state; return ( {items.map(item => ( <ToolbarOption key={item.id}> <Checkbox id={item.id} labelText={item.labelText} value={item.value} checked={item.checked} onChange={this.onChange} /> </ToolbarOption> ))} ) } } 一次,将结果保留为状态。
  • CheckboxItems中,通过onChange找到相关的复选框(lib通过id)并翻转其id标志
  • checked中,从状态中获取render,对于每个项目,使用其items标志,而不是您的`isChecked(我已将其完全删除
相关问题