这可能是一个愚蠢的问题,但我是新的反应,我的下拉菜单有些困难。长话短说,我有一个位置列表,我需要能够“拉出”用户从菜单中选择的位置(我计划使用该位置信息来使用Google的静态地图API生成地图) 。从反应中的下拉菜单中拉取值时出现问题
<form onSubmit={this.handleSubmit}>
<select className="menu" name="select" value={this.state.value} onChange={this.searchLocations}>
{options}
</select>
<input type="submit" value="Submit" />
</form>
(这是产生{选项}的代码):
let options = this.state.locationsBase.map((item, index) => {
return(
<option key={index + 1} value={this.state.locationsBase}>{item.name}</option>
)
})
locationsBase是的加载与componentDidMount阵列。
所以我的问题是这样的: <select value= >
返回'undefined',当我需要它返回用户点击的任何位置(以及位置值包含在{options}中)。 (同样,这些位置都显示在下拉菜单中)。
我不知道这是否非常清楚,但任何帮助将不胜感激。谢谢。
更新
这是searchLocations功能是什么样子:
searchLocations(e){
e.preventDefault()
let selectedLocation = this.locationQuery
console.log(selectedLocation)
this.setState({
locationResults: this.state.selectedLocation
})
selectedLocation
在控制台回报undefined
。
和locationQuery
在我的初始状态下设置为this.value
。
更新(全组分):
class LocationsContainer extends Component {
constructor(props){
super(props)
this.state = {
locationQuery: this.value,
locationResults: "",
locationsBase: []
}
this.handleOnChange = this.handleOnChange.bind(this)
this.searchLocations = this.searchLocations.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
componentDidMount(){
this.setState({
locationsBase:[
{name: "Pick a branch" , address: ""},
{name: "Anacostia" , address: "1800 Good Hope Rd SE"},
{name: "Bellevue" , address: "115 Atlantic St SW"},
{name: "Benning" , address: "3935 Benning Rd NE"},
{name: "Capitol View" , address: "5001 Central Ave SE"},
]
},() => {
console.log(this.state.locationsBase)
})
}
handleOnChange(e) {
const name = e.target.value
this.setState({
[name]: e.target.value
})
console.log("name")
}
searchLocations(e){
e.preventDefault()
let selectedLocation = this.locationQuery
console.log(selectedLocation)
this.setState({
locationResults: this.state.selectedLocation
})
console.log(this.locationResults, 'something is working')
}
handleSubmit(e) {
alert('Your location is: ' + this.state.value);
event.preventDefault();
}
render(){
let options = this.state.locationsBase.map((item, index) => {
return(
<option key={index + 1} value={this.state.locationsBase}>
{item.name}</option>
)
})
return (
<div>
<h3>Choose your branch!</h3>
<form onSubmit={this.handleSubmit}>
<select className="menu" name="select" value={this.state.value}
onChange={this.searchLocations}>
{options}
</select>
<input type="submit" value="Submit" />
</form>
<p>{this.state.locationResults}</p>
</div>
)
}
}
export default LocationsContainer
你的'this.searchLocations'函数是什么样的?它应该更新'this.state.value'。这样,只要你需要选择的值,你就可以抓住'this.state.value' –
你能告诉你如何处理你的状态吗?另外你的'选项'值不应该是相同的数组... – BravoZulu
@StephenL我已更新帖子以包含searchLocations函数。 – edawson