[英]How to pass onChange input value to parent component in React js
I am trying to pass onChange input value from child component to parent component in react js.我正在尝试将 onChange 输入值从子组件传递到反应 js 中的父组件。 I pass with props.
我通过道具。 But in the component, it writes value as
location: <input />
.但是在组件中,它将值写入
location: <input />
。 As I understand it return value as object but when I try to convert with Json.stringfy it returns an error.据我了解,它返回值为 object 但是当我尝试使用 Json.stringfy 进行转换时,它返回一个错误。 So how can pass and set this value in parent component?
那么如何在父组件中传递和设置这个值呢?
class Search extends Component {
// Define Constructor
constructor(props) {
super(props);
render() {
return (
<div>
<Script url="https://maps.googleapis.com/maps/api/jskey=Key&libraries=places"
onLoad={this.handleScriptLoad}
/>
<input onChange={(e)=>this.props.handleChangeSearch(e)} defaultValue={this.props.location} id="autocomplete" placeholder="search city..."
style={{
margin: '0 auto',
maxWidth: 800,
}}
/>
</div>
);
}
}
export default Search;
Main Component主要部件
class MainPage extends Component {
constructor(props) {
super(props);
this.state = {
location: ""
}
}
componentDidMount(){
this.callLoc();
}
handleChangeSearch=(event)=> {
// console.log(JSON.stringify(event.target)+" event");
this.setState({location: event.target});
}
render() {
return (
<div id="main">
<Script url="https://maps.googleapis.com/maps/api/js?key=your_api_key&libraries=places"
onLoad={this.handleScriptLoad} />
<h3 id="mainText">Choose Your Next Destination</h3>
<div id='card'>
<div class="input-group">
<Search handleChangeSearch={this.handleChangeSearch} location={this.state.location}/>
<Button onClick={this.searchLoc}>Search</Button>
</div>
<br></br>
<Button onClick={()=>this.callLoc()} block>Near by Guides</Button>
</div>
</div>
);
}
event.target
will just point to the element that generated this event, you need to use event.target.value
to get the value of the input. event.target
将只指向生成此事件的元素,您需要使用event.target.value
来获取输入的值。
React uses synthetic events (or read here ), so passing the event object can lead to a stale object. React 使用合成事件(或在此处阅读),因此传递事件 object 可能导致过时的 object。
// Pass the value and not the event object
<input onChange={ (e) => this.props.handleChangeSearch(e.target.value) } />
// Fix the handler
handleChangeSearch = (value) => { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.