如何在react js中获取Select Box(它是一个组件)的值

How to get value of Select Box (which is a component) in react js?

本文关键字:一个 的值 组件 Box react js Select 获取      更新时间:2023-09-26

我已经创建了SELECT下拉式可重用组件,我通过导入该组件在不同页面的表单中使用该组件。如何在提交表格时获得选择的值?

    import React from 'react';
    export default class Combobox extends React.Component {    
        render() {
            return (
            <div className="combobox-wrapper">
                <select className="form-control">
                {
                    this.props.combolist.map(function(item, i) {
                      return (
                        <option key={i} value={item.name}>{item.name}</option> 
                      ) 
                    })
                  }
                </select>
            </div>
        );
        }
    }
    import React from 'react';
    import Combobox from '../components/Combobox';
    export default class Home extends React.Component {
    submit(event){
            //how to get combobox (Select list) value here
    } 
    render() {
           var comboList = [{name: 'Self'},{name: 'Mother'},
               {name: 'Father'},{name: 'Domestic Partner'}];
            return (
                <div>
                    <div className="col-lg-10 col-md-10 col-sm-10 marginTop20">
                    <form ref="form" onSubmit={this.submit.bind(this)} >
                        <div className="row">
                            <Combobox combolist={comboList} />
                       </div>
        <div className="row">
                            <input type="submit" value="submit"
              className="btn btn-primary" />
                       </div>
    </form>

如果要使用refs引用选择框,则需要为其指定一个名称。

https://codepen.io/jzmmm/pen/AXaZPp?editors=0011

您的组合框:

<Combobox name="mySelect" combolist={comboList} />

在您选择的组件中添加名称:

<select name={this.props.name} className="form-control">

然后要获得值,您的提交函数:

  submit(event){
    event.preventDefault();
    console.log(this.refs.form.mySelect.value)
  } 

我建议添加自定义函数PropType,每次用户选择新选项时都会调用它。

首先,将其添加到您的组合框中。

ComboBox.propTypes = {
    onOptionChange: React.PropTypes.func.isRequired
}

然后,使option可点击,并让它调用传递的函数。更改:

<option key={i} value={item.name}>{item.name}</option>

<option key={i} value={item.name} onClick={(e) => this.props.onOptionChange(item)>{item.name}</option>

当然,将函数传递给ComboBox,如下所示:

<ComboBox combolist={combolist} onOptionChange={this.onOptionChange.bind(this)} />

现在,每当用户单击任何<option>时,都会调用包含相应项目的onOptionChange函数。(当然,您需要在Home组件中实现它。