[英]How to get value of Select Box (which is a component) in react js?
I have created SELECT drop down reusable component, which I am using in a form at different page by importing that component.
我创建了SELECT下拉可重用组件,该组件通过导入该组件在其他页面的表单中使用。 How do i get the value of selection on submit of form?
我如何在提交表格时获得选择的价值?
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>
You need to give your select box a name if you want to reference it using refs. 如果要使用引用引用选择框,则需要为其命名。
https://codepen.io/jzmmm/pen/AXaZPp?editors=0011 https://codepen.io/jzmmm/pen/AXaZPp?editors=0011
Your combobox: 您的组合框:
<Combobox name="mySelect" combolist={comboList} />
In your select component add the name: 在选择组件中添加名称:
<select name={this.props.name} className="form-control">
Then to get the value, your submit function: 然后获取值,您的Submit函数:
submit(event){
event.preventDefault();
console.log(this.refs.form.mySelect.value)
}
I would suggest adding custom function PropType which will be called every time user select new option. 我建议添加自定义函数PropType,每次用户选择新选项时都会调用它。
First, add this to your ComboBox. 首先,将其添加到您的ComboBox。
ComboBox.propTypes = {
onOptionChange: React.PropTypes.func.isRequired
}
Then, make option
clickable and let it invoke passed function. 然后,使
option
可单击,并使其调用传递的函数。 Change: 更改:
<option key={i} value={item.name}>{item.name}</option>
to 至
<option key={i} value={item.name} onClick={(e) => this.props.onOptionChange(item)>{item.name}</option>
And of course pass function to your ComboBox
like this: 当然,将函数传递给
ComboBox
就像这样:
<ComboBox combolist={combolist} onOptionChange={this.onOptionChange.bind(this)} />
Now your onOptionChange
function containing corresponding item will be invoked every time user click any <option>
. 现在,每次用户单击任何
<option>
时,都会调用包含相应项目的onOptionChange
函数。 (of course you need to implement it in Home
component. (当然,您需要在
Home
组件中实现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.