react如何获取option的下标和值_select选中获取索引三种写法
时间: 2024-01-29 12:46:50 浏览: 31
获取option的下标和值:
1. 使用原生JavaScript的selectedIndex和value属性
```javascript
const selectElement = document.getElementById('mySelect');
const index = selectElement.selectedIndex;
const value = selectElement.value;
console.log("选中项的索引:" + index);
console.log("选中项的值:" + value);
```
2. 使用React组件的onChange事件
```javascript
class MySelect extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
console.log("选中项的索引:" + event.target.selectedIndex);
console.log("选中项的值:" + event.target.value);
}
render() {
return (
<select value={this.state.value} onChange={this.handleChange}>
<option value="apple">苹果</option>
<option value="banana">香蕉</option>
<option value="orange">橙子</option>
</select>
);
}
}
```
获取选中项的索引:
3. 使用ref属性获取DOM元素,然后使用selectedIndex属性
```javascript
class MySelect extends React.Component {
constructor(props) {
super(props);
this.selectRef = React.createRef();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const selectElement = this.selectRef.current;
console.log("选中项的索引:" + selectElement.selectedIndex);
}
render() {
return (
<div>
<select ref={this.selectRef}>
<option value="apple">苹果</option>
<option value="banana">香蕉</option>
<option value="orange">橙子</option>
</select>
<button onClick={this.handleClick}>获取选中项的索引</button>
</div>
);
}
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)