处理 React 中多个输入字段的可用性(禁用)

Handle availability(disable) for multiple input fields in React

我想管理多个输入字段的 'disable' 属性。我创建了一个大表单(超过 30 个输入),其中几个只有在选中前一个复选框时才可用。

我当前的设置类似于下面的示例。在此示例中,如果 'newsletter' 被 select 编辑,您只能 select 'special_offers'。

class Form extends React.Component {
  state={
     newsletter: false,
     specialOffers: false,
     disabled:true,
}

  handleChangeCheck = name => e => {
    this.setState({
      [name]: e.target.checked
    });
    if (name === 'newsletter') {
      this.checkNewsletterValue()
    }
  };
  checkNewsletterValue() {
    if(this.state.newsletter === true){ 
    this.setState( {disabled: !this.state.disabled} )
  } 
}
  render() {
    return(
        <div>

            <Checkbox name="newsletter" value={this.state.newsletter} 
            onChange={handleChangeCheck('newsletter')}>Sign up for news letter
            </Checkbox>

            <Checkbox name="special_offers" value={this.state.specialOffers} 
            onChange={handleChangeCheck('specialOffers')}  disabled = 
            {this.state.disabled}>
            Sign up special offers
            </Checkbox>

        </div>
    );
  }
};

我的问题是,如果我需要创建一个新状态来更改依赖于先前 [=24= 的每个输入字段的 'disable' 属性,我最终会得到一个更大的状态]离子。

有没有办法创建一个通用解决方案来处理我的输入字段的所有 'disable' 值?

好吧,您可以尝试使用 hooks,而不是经典组件。它会减少膨胀,而且通过一些自定义挂钩,您可以将整个函数减少到只有一个函数,您只发送选中的函数和选中的复选框影响的复选框

What is a Hook? A Hook is a special function that lets you “hook into” React features. For example, useState is a Hook that lets you add React state to function components. We’ll learn other Hooks later.

When would I use a Hook? If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component. We’re going to do that right now!

What's a Hook?

顺便说一句,不要"try" hooks,如果你在你的APP里还可以,把它们移到hooks上,它们更干净更快。

假设每个 input 都有一个密钥,每个 checkbox.

都有一个密钥

在这种情况下,我们有 newsletterspecial_offers

我提议的场景是让数组处于状态: - checkedBoxes - 存储控制是否允许其他框的框名称的值。

在您的默认 handleChangeCheck 中,每次选中一个框时,我们都会将其名称推送到数组中。

  handleChangeCheck = name => e => {
    let newCheckedBoxes = [...this.state.checkedBoxes]//don't forget to add a default value for that in the state as an array.
    //conditionally add or remove the items.
    if(newCheckedBoxes.indexOf(name)){
        newCheckedBoxes = newCheckedBoxes.filter(_name => _name !== name);
    } else {
        newCheckedBoxes.push(name);
    }
    e.target.checked && newCheckedBoxes.push(name)
    this.setState({
      [name]: e.target.checked,
      checkedBoxes: newCheckedBoxes,
    });
  };

并在您有条件禁用的框中。

<Checkbox
  name="special_offers"
  value={this.state.specialOffers} 
  onChange={handleChangeCheck('specialOffers')}
  disabled={!this.state.checkedBoxes.includes('newsletter')}>
    Sign up special offers
</Checkbox>