在应用验证函数React js后允许取消选中复选框的问题

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

我有一个选择限制功能,确保总复选框高于最小值,并且在最大值之下,这些值取自复选框映射到的JSON,但如果最小值大于1,则会出现问题,因为函数确实如此-1如果最小值为2,则剩余1个复选框。您可以从演示中看到订单1和订单2之间的差异。

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

注意:我允许稍后取消选择添加警告标志并能够在所选选项之间切换,我试图找到一种逻辑方法,无论最小值如何,都可以取消选择。

功能

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;
      }
    }
  }
javascript reactjs validation checkbox ecmascript-6
1个回答
0
投票

所以一般来说,从dom元素中获取状态会让你头疼。只需跟踪数组中有没有被点击的内容,然后根据它是否在数组中设置checked prop。

然后你不需要增加或减少任何东西,只需检查数组长度,以了解它是否高于或低于最小/最大道具。

第1步:添加数组以跟踪已检查的内容

this.state = {
   .. other stuff ..
   checkedList: []
};

步骤2:根据它是否在数组中设置检查值

<input
  ...
  checked={this.state.checkedList.includes(
    this.props.childk + (item.name || item.description)
  )}
  ...
/>

第3步:简化onChange处理程序:

selectData(id) {
  if (
    !this.state.checkedList.includes(id) &&
    this.state.checkedList.length < this.props.max
  ) {
    this.setState({ checkedList: [...this.state.checkedList, id] });
  } else if (this.state.checkedList.includes(id)) {
    this.setState({
      checkedList: this.state.checkedList.filter(x => x !== id)
    });
  }
}

第4步:使你的onChange处理程序匹配

<input
  ...
  onChange={() =>
    this.selectData(
      this.props.childk + (item.name || item.description)
    )
  }
  ...
/>

codesandbox

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