有条件禁用的React复选框 [英] Conditionally disabled React Checkboxes

查看:37
本文介绍了有条件禁用的React复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建复选框列表,并且只希望用户能够选择2个复选框,然后它将禁用该复选框.我有一个禁用的道具,可以传递布尔值,但是在禁用复选框的逻辑上遇到麻烦.

I am building out a listing of checkboxes and only want the user to be able to select 2 checkboxes and then it will disable the checkboxes. I have a disabled prop which I can pass a boolean but having trouble with the logic to disable the checkbox.

<UISelectableButton
    key={i}
    block={true}
    value={workflow}
    disabled={selectedRevisions > 1 && true}
    onSelectedChange={this.onSelectedChange}
    onClick={() => this.handleRevisions(workflow)}
    type="checkbox"
/>

对于onSelectedChange,我有一个函数可以保存当前选中的复选框的索引.通过执行 selectedRevisions> ;,我可以使用三元运算符轻松禁用按钮.2 ,那么只要选择了2个以上的项目,就可以禁用按钮.这样做的问题是将禁用所有按钮,而我不想禁用已选择的任何按钮.有没有一种方法可以检查是否已选中该复选框,并且仍然将 disabled 传递给布尔值而不是函数.

For the onSelectedChange I have a function that will hold the index of how many checkboxes are currently selected. I can easily disable the buttons with a ternary operator by doing selectedRevisions > 2 then anytime there are more than 2 items selected then I disable the buttons. The problem with this is that will disable all the buttons and I don't want to disable any buttons that have been selected. Is there a way to check if the checkbox has been selected and still pass disabled a boolean and not a function.

推荐答案

您可以将对象保持在可跟踪复选框值的状态,并且在渲染方法中,您可以检查是否选中了2个或更多复选框并使用它禁用其他功能.

You could keep an object in state that keep track of the checkbox values, and in your render method you can check if there are 2 or more checkboxes that are checked and use this to disable the others.

示例

class App extends React.Component {
  state = { checked: {} };

  onSelectedChange = index => {
    this.setState(previousState => ({
      checked: {
        ...previousState.checked,
        [index]: !previousState.checked[index]
      }
    }));
  };

  render() {
    const { checked } = this.state;
    const checkedCount = Object.keys(checked).filter(key => checked[key]).length;
    const disabled = checkedCount > 1;

    return (
      <div>
        {Array.from({ length: 5 }, (_element, index) => (
          <input
            key={index}
            onChange={() => this.onSelectedChange(index)}
            type="checkbox"
            checked={checked[index] || false}
            disabled={!checked[index] && disabled}
          />
        ))}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

这篇关于有条件禁用的React复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆