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



我有多个类别,每个类别都包含多个复选框,为此,我希望使用 React js 一次在每个类别中只选中 1 个复选框。这就是我想要的

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

无法使用单选按钮,因为用户应该能够取消选中所选内容

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

回答您的问题:

// 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>

相关内容

最新更新