react如何获取option的下标和值_select选中获取索引三种写法
时间: 2023-11-27 16:53:10 浏览: 71
React 中获取 `<select>` 组件中选中的 `<option>` 的下标和值可以有以下三种写法:
1. 使用 `event.target` 获取下标和值:
```jsx
handleChange = (event) => {
const selectedIndex = event.target.selectedIndex;
const selectedOption = event.target[selectedIndex];
console.log(selectedIndex, selectedOption.value);
}
render() {
return (
<select onChange={this.handleChange}>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
);
}
```
2. 使用 `ref` 获取下标和值:
```jsx
constructor(props) {
super(props);
this.selectRef = React.createRef();
}
handleChange = () => {
const selectedIndex = this.selectRef.current.selectedIndex;
const selectedOption = this.selectRef.current[selectedIndex];
console.log(selectedIndex, selectedOption.value);
}
render() {
return (
<select ref={this.selectRef} onChange={this.handleChange}>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
);
}
```
3. 使用 `value` 和 `selectedIndex` 获取下标和值:
```jsx
constructor(props) {
super(props);
this.state = {
selectedIndex: 0,
selectedValue: 'apple'
};
}
handleChange = (event) => {
this.setState({
selectedIndex: event.target.selectedIndex,
selectedValue: event.target.value
});
}
render() {
return (
<select value={this.state.selectedValue} onChange={this.handleChange}>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
);
}
```
以上三种写法都可以获取选中的 `<option>` 的下标和值,具体使用哪种取决于你的需求。
阅读全文