如何使用reactjs组件在组中仅选择一个复选框

时间:2019-06-03 10:24:29

标签: javascript reactjs

我有多个类别,每个类别包含多个复选框,为此,我希望使用React js一次只能在每个类别中选中1个复选框。 This is what i want

onlyOne(event) {
    console.log("==",event.target.value)
    var checkboxes = document.getElementsByName('check')
    console.log("cheek",checkboxes);
    checkboxes.forEach((item) => {
      if (item !== event.target.name) item.checked = false
    })

}

HTML:

       <div>
        <label>RBA CONFIGURATION SCREEN </label><br/>               
        View  <input type="checkbox" name="check" value="0" onClick={this.onlyOne.bind(this)} checked=''/>
        Manage  <input type="checkbox" name="check" value="1" onClick={this.onlyOne.bind(this)} checked='' />
        Edit  <input type="checkbox" name="check" value="2" onClick={this.onlyOne.bind(this)} checked='' />
        </div>

在Reactjs中看起来像这样 https://stackoverflow.com/a/37002762

单选按钮无法使用,因为用户应该可以取消选中选择

1 个答案:

答案 0 :(得分:1)

我建议您根据情况切换到收音机。

回答您的问题:

// amount of checkboxes
const n = 3;

class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      // checked/unchecked is stored here
      // initially the first one is checked:
      // [true, false, false]
      checkboxes: new Array(n).fill().map((_, i) => !i),
    };
  }
  onChange(e, changedIndex) {
    // it is a good habit to extract things from event variable
    const { checked } = e.target;
    
    this.setState(state => ({
      // this lets you unselect all.
      // but selected can be anly one at a time
      checkboxes: state.checkboxes.map((_, i) => i === changedIndex ? checked : false),
    }));
  }
  render() {
    const { checkboxes } = this.state;
    
    return (
      <div>
        {checkboxes.map((item, i) => (
          <input
            key={i}
            type="checkbox"
            checked={item}
            onChange={e => this.onChange(e, i) /* notice passing an index. we will use it */}
          />
        ))}
      </div>
    );
  }
}

ReactDOM.render(<Example />, document.querySelector('#root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>