有一种聪明的方法可以在React中禁用多个div吗?

时间:2019-11-13 09:57:41

标签: reactjs frontend

考虑以下代码,其中必须禁用多个div:

<Select disabled={isDisabled}>
 ...
</Select>
<Input disabled={isDisabled}>
 ...
</Input>
<Button disabled={isDisabled}>
 ...
</Button>

有没有更好的方法,例如

divsToDisable = [ select, input, button ];
 ...
func() // being a function that returns true or false based on the div that is calling it
{
...
}

<Select disabled={func()}>
 ...
</Select>
<Input disabled={func()}>
 ...
</Input>
<Button disabled={func()}>
 ...
</Button>


2 个答案:

答案 0 :(得分:1)

按照您的示例:

divsToDisable = ['select','input','button'];
 ...
const isDisabled = (control) => divsToDisable.includes(control) // being a function that returns true or false based on the div that is calling it

<Select disabled={isDisabled('select')}> // true
 ...
</Select>
<Input disabled={isDisabled('input')}> // true
 ...
</Input>
<Button disabled={isDisabled('button')}> // true
 ...
</Button>
<TextArea disabled={isDisabled('textarea')}> // false
 ...
</TextArea>

实时演示:

const divsToDisable = ['select','input','button'];


function App({ divsToDisable }) {

  const isDisabled = (control) => divsToDisable.includes(control);

  return (
    <div>
      <select disabled={isDisabled('select')}>
       <option>1</option>
       <option>2</option>
      </select><br /><br />
      <input type="text" disabled={isDisabled('input')} /><br /><br />
      <button disabled={isDisabled('button')}>Button</button><br /><br />
      <textarea disabled={isDisabled('textarea')}>
       Text Area
      </textarea>
    </div>
  )
}

ReactDOM.render(<App divsToDisable={divsToDisable}  />, document.getElementsByTagName('body')[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>

答案 1 :(得分:1)

如果您尝试实现表单(由于正在使用输入而进行猜测),则可以表征要在字段集中禁用的输入,并将字段集的已禁用属性设置为确实,这将导致禁用字段集中的所有输入,这是HTML的一种简单实现。

enter image description here

您在组件内部的渲染函数将如下所示:-

isDisabled = () =>{
    //disabling logic
}

render() {
  return (
    <form>
      <fieldset disabled={this.isDisabled()}>
        <legend>Personalia:</legend>
        Name: <input type="text" />
        Email: <input type="text" />
        Date of birth: <input type="text" />
      </fieldset>
    </form>
  );
}

但是,如果您不需要禁用任何表单字段,则在要禁用的所有div上使用包装器,并在div上添加覆盖以创建禁用效果,例如here