[英]React: Can't select dropdown menu options after assigning value attribute to component's state
I have a React component that renders a dropdown menu.The component's state is updated when it receives props from its parent. 我有一个可渲染下拉菜单的React组件,当组件从其父对象接收道具时会更新其状态。 I've set the 'value' attribute of the <'select> element to the state so that it re-renders when new props are received. 我已经将<'select>元素的'value'属性设置为状态,以便在收到新道具时重新渲染。 This successfully re-renders the value in the dropdown menu when props are received but disables it from selecting a different option. 当收到道具时,这将成功地在下拉菜单中重新渲染该值,但使它无法选择其他选项。
<select
type="text"
name="dogOwnerType"
id="dogOwnerType"
className="form-control"
data-bv-field="dogOwnerType"
value={this.state.dogOwnerType.ownerType}
>
<option value="">Choose Owner Type</option>
<option value="DogLover">DogLover</option>
<option value="DogOwner">DogOwner</option>
</select>
To be able to change the value; 能够更改值; you should add an onChange handler, which sets the new value to the state. 您应该添加一个onChange处理函数,该处理函数会将新值设置为状态。
// define function which sets new value to state
updateOwnerType = event => {
this.setState({
dogOwnerType: {
...this.state.dogOwnerType,
ownerType: event.target.value,
})
}
{/* add your onChange handler to select element */}
<select
type="text"
name="dogOwnerType"
id="dogOwnerType"
className="form-control"
data-bv-field="dogOwnerType"
onChange={this.updateOwnerType}
value={this.state.dogOwnerType.ownerType}
>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.