React 中有条件地禁用选择选项

编程入门 行业动态 更新时间:2024-10-09 20:26:17
本文介绍了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 中有条件地禁用选择选项

本文发布于:2023-11-23 00:43:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619508.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中有   选项   条件   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!