我有一个 FormControl,它是我在表单中使用的 Select。添加新资源时效果很好,但是当我想编辑现有记录时,我需要设置控件的值。我没有看到设置选择/组合框值的好方法。这就是我的 JSX 的样子。
<FormGroup controlId="group">
<ControlLabel>Group</ControlLabel>
<FormControl componentClass="select" placeholder="Group"
inputRef={ref => { this.groupSelect = ref; }}
onChange={this.groupSelect}>
<option></option>
{
this.state.groups.map(function (group) {
return <option key={group.id} value={group.id}>{group.name}</option>
})
}
</FormControl>
</FormGroup>
我试过以这种方式访问该组件,但它未定义。
console.debug(this.groupSelect);
this.groupSelect.value(1);
更新:
我正在尝试以下操作,但这似乎也不起作用,因为我在该状态下没有访问权限,调用绑定(bind)会导致错误。
<FormGroup controlId="group">
<ControlLabel>Group</ControlLabel>
<FormControl componentClass="select" placeholder="Group"
inputRef={(ref) => { this.state.groupSelect = ref }}
onChange={this.groupSelect}>
<option></option>
{
this.state.groups.map(function (group) {
return <option key={group.id} value={group.id} selected={this.state.selectedGroupId == group.id}>{group.name}</option>
}).bind(this)
}
</FormControl>
</FormGroup>
最佳答案
您在这里遗漏了一个关键部分,即您需要设置组件的值。添加:
value={this.state.groupSelectValue || defaultValue}
groupSelectValue
是您正在编辑的记录中的值,defaultValue
是您在没有记录或记录。
然后,在 onChange
事件函数 (groupSelect(e)
) 中,您将执行:
this.setState({
groupSelectValue: e.target.value
});
以便状态随选择更新。
关于javascript - React-Bootstrap 设置 FormControl Select 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42446542/