我有一个选择值属性,它是{board.id},但我还需要访问{board.name},无论如何我可以让另一个属性工作?
我做了例子= {board.name}但没有成功..
handleChange(event){
this.setState({value: event.target.value});
this.setState({example: event.target.example});
}
let boards = this.state.boards;
let optionItems = boards.map((board) =>
<option key={board.id} value={board.id} example={board.name} >{board.name}</option>);
<select value={this.state.value} onChange={this.handleChange} className="custom-select dropbox">
{optionItems}
</select>
答案 0 :(得分:2)
以下内容适合您。
class App extends Component {
handleChange(event){
let index = event.target.selectedIndex;
let el = event.target.childNodes[index]
let option = el.getAttribute('example');
}
render() {
return (
<select value={'test'} onChange={this.handleChange} className="custom-select dropbox">
<option value={'test1'} example={'testKey1'}>Test1</option>
<option value={'test2'} example={'testKey2'}>Test2</option>
<option value={'test3'} example={'testKey3'}>Test3</option>
</select>
);
}
}
您忘记了需要选项的索引。
答案 1 :(得分:1)
Sasha只返回选择字段本身的示例属性,而不是选项的示例属性。
答案 2 :(得分:1)
class App extends React.Component {
handleChange = (e) => {
const { selectedIndex, options } = e.target;
const selectedOption = options[selectedIndex];
console.log('NAME: ' + selectedOption.dataset.name)
console.log('VALUE: ' + selectedOption.value)
}
render () {
return (
<div>
<select
onChange={this.handleChange}>
<option value=''>-select option-</option>
<option value='1' data-name='name1'>1</option>
<option value='2' data-name='name2'>2</option>
<option value='3' data-name='name3'>3</option>
</select>
</div>
)
}
}
答案 3 :(得分:0)
您可以通过选定的ID找到完整对象:
handleChange(event) {
const {boards} = this.props;
const selectedBoard = boards.find((board) => board.id === event.target.value);
}