2 回答

TA貢獻1155條經驗 獲得超0個贊
您正在使用this.state.value但正在更新this.state.selectedOption. 兩者必須相同。我認為您正在使用 Material UI Select 所以我也這樣做:
import React, { Component } from "react";
import { Select, MenuItem } from '@material-ui/core';
class Test extends Component {
state = {
selectedOption: ""
};
handleChange = selectedOption => {
this.setState({
selectedOption
});
console.log(selectedOption);
};
render() {
let options = [];
if (this.state.cityName && this.state.cityName.length > 0) {
options = this.state.cityName.map(cityName => {
return {
value: cityName.AdministrativeArea.LocalizedName,
label: cityName.AdministrativeArea.LocalizedName,
id: cityName.Key
};
});
}
const { selectedOption } = this.state;
return (
<div className="container">
<h1 htmlFor="Search">Search</h1>
<Select
name="htmlForm-field-name"
value={selectedOption}
onChange={e => this.handleChange(e.target.value)}
>
{options.map(o => <MenuItem value={o.value}>{o.label}</MenuItem>)}
</Select>
<div>
<ul>{selectedOption}</ul>
</div>
</div>
);
}
}
export default Test;

TA貢獻1836條經驗 獲得超5個贊
工作示例:
import React, { Component } from "react";
import Select from "react-select";
class App extends Component {
handleChange = el => {
console.log(el.value);
};
render() {
return (
<div>
<Select
style={{ width: 100 }}
onChange={this.handleChange}
options={[
{ value: "green", label: "Green", color: "#36B37E" },
{ value: "forest", label: "Forest", color: "#00875A" },
{ value: "slate", label: "Slate", color: "#253858" },
{ value: "silver", label: "Silver", color: "#666666" }
]}
/>
</div>
);
}
}
export default App;
添加回答
舉報