javascript - React-Bootstrap 设置 FormControl Select 的值

标签 javascript reactjs react-bootstrap

我有一个 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/

相关文章:

javascript - 将过滤器应用于列表并显示数据

javascript - react Jest enzyme : testing callback of child component that calls another function first before calling the callback

javascript - 如何可靠地测量 React 组件的弹出框和标注的计算位置?

Javascript改变html元素的绝对位置

javascript - 计算 javascript 字符串中字符的出现次数

reactjs - 从另一个选择选项更新选择 react

reactjs - 如何在azure云上托管grafana?

reactjs - 如何在 NextJS 中创建轮播?

javascript - Angular/Javascript 搜索对象键数组

javascript - 将 bootstrap-growl 警报左下角对齐