我现在有这样的下拉菜单。它的工作是我根据需要获取价值,但是当value是一个对象时,如何在下拉列表中获取名称会发生变化。有什么想法吗?
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>
答案 0 :(得分:0)
要获取安装名称,只需使用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>
答案 1 :(得分:0)
我这样做,将值作为下拉列表中的索引,然后将该索引分配给对象数组,并获取我需要的对象值:
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>