Conditionally disabled React Checkboxes

后端 未结 2 797
南旧
南旧 2021-01-05 20:42

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 ca

2条回答
  •  难免孤独
    2021-01-05 21:23

    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.

    Example

    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 (
          
    {Array.from({ length: 5 }, (_element, index) => ( this.onSelectedChange(index)} type="checkbox" checked={checked[index] || false} disabled={!checked[index] && disabled} /> ))}
    ); } } ReactDOM.render(, document.getElementById("root"));
    
    
    
    

提交回复
热议问题