React JSX:选择“已选择”选中< select>选项 [英] React JSX: selecting "selected" on selected <select> option
问题描述
在< select>
菜单的React组件中,我需要设置选中的
属性反映应用程序状态的选项。
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组件。选项值从JSON传递为 props
。
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会自动为此目的理解布尔值,因此您只需编写(注意:不推荐)
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让你更容易。不是在每个选项上定义选择
,而是你可以(而且应该)只写 value = {optionsState}
选择标记本身:
However, 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 select tag doc 。
For more info, see the React select tag doc.
这篇关于React JSX:选择“已选择”选中< select>选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!