Reactjs 将子组件的状态传递给父组件?

Reactjs 将子组件的状态传递给父组件?,reactjs,components,state,Reactjs,Components,State,我想我知道我需要做什么才能使我的searchLocationChange功能正常工作,但我不知道该怎么做。请原谅这个缩进,我们正在努力解决StackOverflow的WYSIWYG 以下是我的父组件设置: 类应用程序扩展了React.Component{ 建造师(道具){ 超级(道具); 此.state={ 预测:[], 地点:{ 城市:'', 国家:“, }, 所选日期:0, 搜索文本:“”, }; this.handleForecastSelect=this.handleForecastSe

我想我知道我需要做什么才能使我的
searchLocationChange
功能正常工作,但我不知道该怎么做。请原谅这个缩进,我们正在努力解决StackOverflow的WYSIWYG

以下是我的父组件设置:

类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
预测:[],
地点:{
城市:'',
国家:“,
},
所选日期:0,
搜索文本:“”,
};
this.handleForecastSelect=this.handleForecastSelect.bind(this);
this.searchLocationChange=this.searchLocationChange.bind(this);
}
}
有了这个特定的功能,我想让它发挥作用:

searchLocationChange(){
console.log(this.state.searchText);
Axios.get()https://mcr-codes-weather.herokuapp.com/forecast', {
参数:{
城市:this.state.searchText,
},
})
。然后((响应)=>{
这是我的国家({
预测:响应。数据。预测,
地点:{
城市:response.data.location.city,
国家:response.data.location.country,
}
});
});
}
在我的子组件中,逻辑是:

类SearchForm扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
搜索文本:“”,
};
this.handleInputChange=this.handleInputChange.bind(this);
}
handleInputChange(事件){
const enteredText=event.target.value;
这是我的国家({
searchText:enteredText
});
}
render(){
返回(
搜寻
);
}
}

我意识到我正试图用子组件状态中的searchText更新父组件,但我不知道需要做哪些更改才能使其正常工作。我有一种隐秘的怀疑,我已经完成了99%的任务,而且我只需要再多几行,但我可能已经完成了?

你应该像这样调用函数
this.props.searchLocationChange(this.state.searchText)

你可以像下面这样做

{this.props.searchLocationChange(this.state.searchText)}>Search
函数定义应该是

searchLocationChange(searchText){

您已经从您的父母那里继承了
searchLocationChange

在父组件中:

searchLocationChange(searchedText){
console.log(searchText);
Axios.get()https://mcr-codes-weather.herokuapp.com/forecast', {
参数:{
城市:搜索文本,
},
})
。然后((响应)=>{
这是我的国家({
预测:响应。数据。预测,
地点:{
城市:response.data.location.city,
国家:response.data.location.country,
},
});
});
}
儿童:

render(){
const{searchText}=this.state;
返回(
{this.props.searchLocationChange(searchText)}>Search
);
}

您在控制和不控制混合。要么受控,要么不受控。因此,仅从父级获取搜索文本。上述解决方案是实现这一点的一种方法。另一种方法是将searchTxt从父级传递给子级


移动您的手在父项中输入更改:

handleInputChange=(事件)=>{
const enteredText=event.target.value;
this.setState({searchText:enteredText});
}
然后将子组件的相应行更改为



现在,当您尝试上面的代码时,它应该可以工作了。现在,您将searchTxt保存在父组件中。您的SearchForm组件现在已完全受控。

您正在onclick searchLocation中调用该函数。将其更改为onClick={()=>this.props.searchLocationChange(searchText)}@simbathesaller感谢您指出这一点。我真的错过了。非常感谢你的帮助–非常感谢。非常感谢–感谢!