简体   繁体   English

FormControl Select 的 React-Bootstrap 设置值

[英]React-Bootstrap set value of FormControl Select

I have a FormControl which is a Select that I am using in a form.我有一个 FormControl,它是我在表单中使用的 Select。 It works fine when adding a new resource, but when I want to edit an existing record I need to set the value of the control.添加新资源时它工作正常,但是当我想编辑现有记录时,我需要设置控件的值。 I'm not seeing a good way to set the value of the select / combobox.我没有看到设置选择/组合框值的好方法。 This is what my JSX looks like.这就是我的 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>

I've tried to access the component this way but it comes up undefined.我试图以这种方式访问​​组件,但它未定义。

console.debug(this.groupSelect);
this.groupSelect.value(1);

UPDATE:更新:

I'm trying the following, but this doesn't appear to be working either because I don't have access in the state, calling bind causes an error.我正在尝试以下操作,但这似乎也不起作用,因为我无权访问该状态,调用 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>

You are missing a crucial piece here, which is you need to set the value of the component.您在这里遗漏了一个关键部分,即您需要设置组件的值。 Add:添加:

value={this.state.groupSelectValue || defaultValue}

Where groupSelectValue is the value from the record you're editing, and the defaultValue is what you want to default to if there is no record or no value in the record.其中groupSelectValue是您正在编辑的记录中的值,而defaultValue是您希望在记录中没有记录或没有值时默认使用的值。

Then, in the onChange event function ( groupSelect(e) ), you will do:然后,在onChange事件函数( groupSelect(e) )中,您将执行以下操作:

this.setState({
 groupSelectValue: e.target.value
});

So that the state is updated with the selection.这样状态就会随着选择而更新。

所选值应来自模型(状态或属性),您正在尝试使用 'jquery 方式' 实现所需的内容 - 这是错误的。

我可能知道如何获取在状态变量选项中选择的键值吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM