问题
I am trying to get the text value from a dropdown select using [useState} in React Hooks. I just get the value (number) rather than the text. Ive copied the bits of code below which control the select dropdown. What am i missing here? Thanks.
const [addrtype, setAddrType] = useState('Home')
function handleAddrTypeChange(e) {
setAddrType(e.target.value);
console.log(addrtype)
}
<select
defaultValue={addrtype}
onChange={handleAddrTypeChange}
className="browser-default custom-select">
<option selected value="1">Home</option>
<option value="2">Marketing</option>
<option value="3">Work</option>
<option value="3">Head Office</option>
</select>
回答1:
import React, { useState, Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
const App = () => {
const [addrtype, setAddrtype] = useState(["Work", "Home", "school"])
const Add = addrtype.map(Add => Add
)
const handleAddrTypeChange = (e) => console.log((addrtype[e.target.value]))
return (
< select
onChange={e => handleAddrTypeChange(e)}
className="browser-default custom-select" >
{
Add.map((address, key) => <option value={key}>{address}</option>)
}
</select >)
}
render(<App />, document.getElementById('root'));
Working example
https://stackblitz.com/edit/react-select-hook
回答2:
If you want text then access text instead of value. event.target.text
.
Check the reference here. http://output.jsbin.com/vumune/4/
回答3:
Just change the option value
<option selected value="Home">Home</option>
<option value="Marketing">Marketing</option>
<option value="Work">Work</option>
<option value="Head Office">Head Office</option>
来源:https://stackoverflow.com/questions/58114855/handling-select-options-in-react-hooks