[英]how to get the key of a selected value from a dropdown in reactjs?
how to bind a json data which has a key-value pair to select html in reactjs, such that It should display the value in the drop-down and If I choose a value , I should provide the relevant key?如何绑定具有键值对的json数据以在reactjs中选择html,以便它应该在下拉列表中显示值,如果我选择一个值,我应该提供相关的键?
For example:例如:
var optionsdata = [
{key='101',value='Lion'},
{key='102',value='Giraffe'},
{key='103',value='Zebra'},
{key='104',value='Hippo'},
{key='105',value='Penguin'}
];
in the drop-down, it should show "Lion","Giraffe","Zebra",... if I choose, Zebra, I should get the select value (Zebra) as well as the key (103, in the above example)在下拉列表中,它应该显示“Lion”、“Giraffe”、“Zebra”,...如果我选择,Zebra,我应该得到选择值(Zebra)以及键(103,在上面例子)
You can simply filter
out the data from the your object once you get get the value of selected option.一旦获得所选选项的值,您就可以简单地从对象中
filter
掉数据。 I have not used controlled input in my example, If you use that it will be even better.我在我的例子中没有使用受控输入,如果你使用它会更好。
class App extends React.Component { constructor() { super(); this.state = { optionsdata : [ {key:'101',value:'Lion'}, {key:'102',value:'Giraffe'}, {key:'103',value:'Zebra'}, {key:'104',value:'Hippo'}, {key:'105',value:'Penguin'} ] } } handleChange = (e) => { console.log(e.target.value); var value = this.state.optionsdata.filter(function(item) { return item.key == e.target.value }) console.log(value[0].value); } render() { return ( <select onChange={this.handleChange}> {this.state.optionsdata.map(function(data, key){ return ( <option key={key} value={data.key}>{data.value}</option> ) })} </select> ) } } ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.min.js"></script> <div id="app"></div>
Hope this answer will help希望这个答案会有所帮助
1) First find selected index which is called key 1)首先找到被称为key的选定索引
var selectedIndex = event.target.options.selectedIndex;
2) If you have custom attribute and want to fetch value of that attribute then 2)如果您有自定义属性并想获取该属性的值,那么
var customAtrribute= event.target.options[selectedIndex].getAttribute('customAtrribute');
Use react-select .使用react-select 。 It is able to handle
id
and value
elegantly.它能够优雅地处理
id
和value
。 Map your id
to react-select value
and your value
to react-select label
.将您的
id
映射到 react-select value
并将您的value
映射到 react-select label
。
You can configure callback which will return you selected value/s.您可以配置回调,它将返回您选择的值/秒。 You can even turn on search.
您甚至可以打开搜索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.