当值为对象时,从选择的对象数组中响应下拉列表



我现在有这样的下拉菜单。它的工作我正在根据需要获取值,但是当值是一个对象时,如何在下拉列表中获取名称更改为选定。有什么想法吗?

onDropdownSelected = (e) => {           
if (e.target.value !== '') {
const inst = JSON.parse(e.target.value)
console.log('inst', inst)           
}
}

<select id="mySelect" onChange={this.onDropdownSelected}>
{installations.map(installation => 
<option key={installation._id} name={installation._id} value= 
{JSON.stringify(installation)}>{installation.name}</option>)}
</select>

要获取安装名称,只需使用inst.name.

我复制了你的例子。 玩一下,随时提出任何相关问题。

class App extends React.Component {
onDropdownSelected = (e) => {           
if (e.target.value !== '') {
const inst = JSON.parse(e.target.value)
console.log('Installation name:', inst.name);
}
}

generateInstallations = () => [...Array(100)].map((val, i) => (
{ _id: `special-${i}`, name: `Installation #${i}` }
));

render() {
const installations = this.generateInstallations();
return (
<div>
<h4>Select your installation:</h4>
<select id="mySelect" onChange={this.onDropdownSelected}>
{installations.map(installation => 
<option
key={installation._id}
name={installation._id}
value={JSON.stringify(installation)}>
{installation.name}
</option>
)}
</select>
</div>
);
}

}
ReactDOM.render(<App />, document.getElementById('react'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="react"></div>

我这样做了,在下拉列表中将值作为索引,只是将此索引分配给对象数组,并获取我需要的对象值:

onDropdownSelected =(e)=>{
if (e.target.value !== '') {    
this.setState({
inst: this.state.installations[e.target.value]
})    

<select onChange={this.onDropdownSelected} disabled >
{this.state.installations.map((option, index) =>
<option key={index} value={index}>
{option.name}
</option>)}
</select>

最新更新