在我的React App中,我有一个文本框,用户可以在其中在Google自动填充框中输入位置-LocationInput
import React, { Component } from 'react'
...
import LocationInput from './location-input'
...
change = (what, e) => this.setState({ [what]: e.target.value })
....
render() {
let {
location,
country,
...
} = this.state
...
...
<LocationInput value={location} change={this.change} />
答案 0 :(得分:2)
您将新位置传递给change
处理程序:
onPlaceSelected={(place) => {
change(getDistrict(place))
}}
这将在外部组件中调用change函数并更新状态。除非出于某种原因onPlaceSelected
被自动再次调用,否则它不会导致无限循环。
答案 1 :(得分:1)
为什么不只具有更改功能,如:
change = location => this.setState({ location })
....
render() {
return <LocationInput value={this.state.location} change={this.change} />
}
然后在孩子中
const LocationInput = ({ value, change }) => {
return (
<div className="edit_location_div">
<Autocomplete
className="locationInput my2"
onPlaceSelected={ place => {
change(getDistrict(place))
}}
placeholder="Enter Nearest MAJOR City"
/>
</div>
)
}
当然,我假设“ onPlaceSelected”返回的数据类型与该状态中存储的数据类型相同。