React JSX:选择“选定"在选定的<选择>上选项 [英] React JSX: selecting "selected" on selected <select> option
问题描述
在用于 菜单的 React 组件中,我需要在反映应用程序状态的选项上设置
selected
属性.
In a React component for a <select>
menu, I need to set the selected
attribute on the option that reflects the application state.
在render()
中,optionState
从状态所有者传递给SortMenu 组件.选项值作为 props
从 JSON 传入.
In render()
, the optionState
is passed from the state owner to the SortMenu component. The option values are passed in as props
from JSON.
render: function() {
var options = [],
optionState = this.props.optionState;
this.props.options.forEach(function(option) {
var selected = (optionState === option.value) ? ' selected' : '';
options.push(
<option value={option.value}{selected}>{option.label}</option>
);
});
// pass {options} to the select menu jsx
然而,这会在 JSX 编译时触发语法错误.
However that triggers a syntax error on JSX compilation.
这样做可以消除语法错误,但显然不能解决问题:
Doing this gets rid of the syntax error but obviously doesn't solve the problem:
var selected = (optionState === option.value) ? 'selected' : 'false';
<option value={option.value} selected={selected}>{option.label}</option>
我也试过这个:
var selected = (optionState === option.value) ? true : false;
<option value={option.value} {selected ? 'selected' : ''}>{option.label}</option>
有没有推荐的方法来解决这个问题?
Is there a recommended way of solving this?
推荐答案
React 使这对您来说更加容易.不必在每个选项上定义 selected
,您可以(并且应该)简单地在 select 标签本身上编写 value={optionsState}
::>
React makes this even easier for you. Instead of defining selected
on each option, you can (and should) simply write value={optionsState}
on the select tag itself:
<select value={optionsState}>
<option value="A">Apple</option>
<option value="B">Banana</option>
<option value="C">Cranberry</option>
</select>
有关详细信息,请参阅React 选择标签文档.
For more info, see the React select tag doc.
此外,React 会为此自动理解布尔值,因此您可以简单地编写(注意:不推荐)
Also, React automatically understands booleans for this purpose, so you can simply write (note: not recommended)
<option value={option.value} selected={optionsState == option.value}>{option.label}</option>
它会适当地输出'selected'.
and it will output 'selected' appropriately.
这篇关于React JSX:选择“选定"在选定的<选择>上选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!