对具有动态生成选项的选择反应defaultValue

Min*_*ngu 6 javascript jquery select reactjs redux

使用defaultValue或值props而不是设置选中.

<select defaultValue="react">
 <option value="react">React</option>
 <option value="angular">Angular</option>
</select>
Run Code Online (Sandbox Code Playgroud)

defaultValue可以使用上面的select标签.但是,它似乎不适用于循环生成的选项.

<select defaultValue={selectedOptionId}>
{option_id.map(id =>
  <option key={id} value={id}>{options[id].name}</option>
)}
</select>
Run Code Online (Sandbox Code Playgroud)

声明defaultValue时可能没有完全设置选项?

我可以手动分配componentDidUpdate()onChange事件.

但我的问题是 - 有没有更清洁(更好)的方法来解决它?

谢谢.

小智 6

这是旧的,但由于答案#1与受控 有关Select,而问题似乎与不受控 Select有关,我认为值得为未来的读者留下一些内容:

问题是,对于uncontrolled组件来说,React 需要知道options 第一次 render 之前的内容是什么,因为从那一刻起,它们defaultValue就不会覆盖Select. 这意味着如果您在Select之前渲染,options它将不知道要选择什么。

render您可以在可用之前避免问题的解决options

const RenderConditionally = ({ options, selected }) => options.length > 0 ? (
  <select defaultValue={selected}>
   {options.map(item => (
     <option key={item.id} value={item.value}>{item.label}</option>
   ))}
  </select>
) : null;
Run Code Online (Sandbox Code Playgroud)

或者如果您愿意,可以不使用三元:

const RenderConditionally = ({ options, selected }) => {
  if (options.length === 0) {
    return null;
  }

  return (
    <select defaultValue={selected}>
      {options.map(item => (
        <option key={item.id} value={item.value}>{item.label}</option>
      ))}
    </select>
  );
};
Run Code Online (Sandbox Code Playgroud)


Ale*_*rev 0

option_id最有可能的是你的数组options结构或变量有问题selectedOptionId。您构建选择组件的方式是可以的。

我做了一个小提琴,这段代码工作正常:

render: function() {
let option_id = [0, 1];
let options = [{name: 'a'}, {name: 'b'}];
let selectedOptionId = 1
return (
  <select defaultValue={selectedOptionId}>
    {option_id.map(id =>
    <option key={id} value={id}>{options[id].name}</option>
    )}
  </select>
)
Run Code Online (Sandbox Code Playgroud)

}