验证reactJS中复选框的简单功能

Alx*_*lxL 11 javascript mapping checkbox ecmascript-6 reactjs

我做了一个选择限制功能,可以确保总复选框高于最小值,低于最大值,这些值取自映射复选框的JSON,现在选择限制有效,但是我试图添加验证以显示使用onblur发出警告,但是我不确定如何将同一函数转换为onblur验证函数。例如,如果某人取消选中,它会在控制台上显示您至少需要选择3直到选中3,这与selectData()的逻辑相同。

功能

  selectData(id, event) {
    let isSelected = event.currentTarget.checked;
    if (isSelected) {
      if (this.state.currentData < this.props.max) {
        this.setState({ currentData: this.state.currentData + 1 });
      } else {
        event.preventDefault();
        event.currentTarget.checked = false;
      }
    } else {
      if (this.state.currentData >= this.props.min) {
        this.setState({ currentData: this.state.currentData - 1 });
      } else {
        event.preventDefault();
        event.currentTarget.checked = true;
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

完整代码:https//codesandbox.io/embed/48o2jo2500?fontsize = 14

Hol*_*yOS 4

您的一般方法似乎应该有效,只需要实际实现错误状态的技巧。不过,这里的建议是更新您的!isSelected && this.state.currentData < this.props.min条件,以允许选择少于三个,但向用户显示错误状态。

  ...
    } else {
      if (this.state.currentData >= this.props.min) {
        // this.setState({ currentData: this.state.currentData - 1 });
        // UPDATE:
        this.setState((state) => ({ currentData: state.currentData - 1 }));
      } else {
        event.preventDefault();
        // Don't force the box to be selected, show error state instead
        // Disable calls to filtering, sorting, etc. until error resolved
        // event.currentTarget.checked = true;
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

基本实现:

  • 请注意,“setState”是异步的,并且像您一样访问先前的“currentData”值是不安全的。你应该写 `this.setState((state) =&gt; ({ currentData: state.currentData - 1 }));` (4认同)