Conditionally disabled select option in React

不打扰是莪最后的温柔 提交于 2019-12-10 12:47:12

问题


I built my own React select component and would like to have an option to set the default value to be disabled

The component basically looks like this:

<select
    id={this.props.id}
    name={this.props.name}
    value={this.props.value}
    defaultValue={this.props.default}
    onClick={this.handleFieldClick}
    onChange={this.handleFieldChange} >

         <option value="" disabled={this.defaultDisabled ? true : false} >{this.props.defaultLabel}</option>

         { Object.keys(this.props.options).map((val, i) => ( 
             <option key={i} value={val}>{this.props.options[val]}</option>
         ))}

 </select>

This line giving me the issue is the following:

<option value="" disabled={this.defaultDisabled ? true : false} >{this.props.defaultLabel}</option>

The "disabled" option is still selectable and renders like this:

<option value="" selected="">Default Option</option>

I believe it's because the correct syntax for a disabled option is <option disabled ></option>, not <option disabled="true" ></option>

But when I format my JSX as follows:

<option value="" {this.defaultDisabled ? "disabled" : ""} >{this.props.defaultLabel}</option>

I get an error that crashes the app.

What is the correct syntax for conditionally writing a directive value into a tag with JXS and/or conditionally set a disabled option in React?


回答1:


You missed a .props. And you can also use null instead of false.

<option value="" disabled={this.props.defaultDisabled ? true : null} >{this.props.defaultLabel}</option>



回答2:


This should work:

    <option 
      value=""
      disabled={this.props.defaultDisabled}
    >
      {this.props.defaultLabel}
    </option>



来源:https://stackoverflow.com/questions/51164838/conditionally-disabled-select-option-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!