选择限制功能不适用于复选框表单reactjs

问题描述 投票:2回答:1

我有一个反应组件,从json获取复选框,复选框的每个部分最多可以包含5个复选框,我试图将每个部分的限制设置为最多2个选项,但它不能正常工作,主要组件是itemlist.js,复选框来自checkbox.js,这里是我想要做的实时片段,https://codesandbox.io/embed/84lo55n689?fontsize=14,更改是在checkbox.js中进行的,我注释掉了函数并且它更改为演示,因为它使应用程序崩溃。

Checkbox.js

    import React from "react";
import "./Checkbox.css";

/* class Checkboxes extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
    currentData: [],
    limit: 2

  }}
 componentDidMount() {

  selectData(id, event){
    let isSelected = event.currentTarget.checked;
    if (isSelected) {
      if (this.state.currentData.length < this.state.limit) {
        this.setState({ currentData: [...currentData, id] })
      }
    }
    else {
      this.setState({
        currentData:
          this.state.currentData.filter((item) => id !== item)
      })
    }
  }}
 render() { */

const Checkboxes = props => {
  const id = /*this.*/ props.childId + /*this.*/ props.childp;

  return (
    <form className="form">
      <div>
        <h2>{/*this.*/ props.title}</h2>
        {/*this.*/ props.options &&
          /*this.*/ props.options.map(item => {
            return (
              <div className="inputGroup">
                <input
                  id={id + item.name}
                  name="checkbox"
                  type="checkbox"
                  //     checked={this.state.currentData.indexOf(id + item.name) >= 0}
                  //  onChange={this.selectData.bind(this, id + item.name)}
                />
                <label htmlFor={id + item.name}>{item.name} </label>
              </div>
            );
          })}
      </div>
    </form>
  );
}; //}}

export default Checkboxes;

Itemlist.js

...

  <Checkboxes
                        key={index}
                        title={item.name}
                        myKey={index}
                        options={item.children}
                        childk={item.id}
                      />
...
javascript reactjs checkbox ecmascript-6 web-applications
1个回答
0
投票

无需知道在全局中检查哪个元素,

首先在this.state中将currentData更改为0

constructor(props) {
    super(props);
    this.state = {
      currentData: 0,
      limit: 2
    };
  }

然后更改selectData函数

selectData(id, event) {
    let isSelected = event.currentTarget.checked;
    if (isSelected) {
      if (this.state.currentData < this.state.limit) {
        this.setState({ currentData: this.state.currentData+1 });
      }else{
        event.preventDefault()
        event.currentTarget.checked = false;
      }
    } else {
      this.setState({currentData: this.state.currentData - 1});
    }
  }

并从输入中删除checked属性(当页面加载为0时)'

<div className="inputGroup">
   <input
       id={id + item.name}
       name="checkbox"
       type="checkbox"
       onChange={this.selectData.bind(this, id + item.name)}
   />
<label htmlFor={id + item.name}>{item.name} </label>
</div>

https://codesandbox.io/s/j4yyx9v6l5?fontsize=14

© www.soinside.com 2019 - 2024. All rights reserved.