React 中有条件地禁用选择选项 [英] Conditionally disabled select option in React

查看:107
本文介绍了React 中有条件地禁用选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建了自己的 React 选择组件,并希望有一个选项可以将默认值设置为 disabled

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

组件基本上是这样的:

<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>

但是当我按如下方式格式化 JSX 时:

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.

在 React 中使用 JXS 有条件地将指令值写入标签和/或有条件地设置禁用选项的正确语法是什么?

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?

推荐答案

您错过了 .props.你也可以使用 null 而不是 false.

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>

这篇关于React 中有条件地禁用选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆