在子组件上运行函数,在父组件上调用函数



我想从一个国家的变化中获取状态,并将handleChange传递给父组件,所以在子组件上,我呈现以下内容:

<select  className="floating-select"
id = "country"
type ="text"
onChange={handleChange('country')}>
<option value="" selected>Please select a state</option>
{
this.state.countries.map(country => (
<option value ={country}>{country}</option>
))
}
</select>

我将handleChange传递给父级,如下所示

handleChange = input => e =>{
this.setState({[input]:e.target.value} );
} 

我的问题是如何在子组件上运行一个函数来获取数据(下面的状态到那个国家),并且仍然将handleChange('country')传递给父组件

永远不要在react中向组件树传递任何东西。这是反应的核心原理之一。如果你想在父类和子类中都有访问权限,那就在父类中定义它,然后传递给子类。所以定义状态和逻辑状态。

编辑:不得不在这里回复你的评论,评论太小了。

您需要知道当前选择了哪个国家,是的,但是您也将该信息保存在状态中,并在处理程序中更新它。所以你的状态看起来像

{
countries: [...listOfAllCoiuntries], 
country: selectedCountry or undefined, 
...otherStateProps
} 

在你的handleChange函数中,你将国家道具设置为该选项的值,所以你的父类可以通过this.state.country访问哪个选项被选中了。如果你通过props将this.state.country传递给你的子组件,那么你可以通过value prop将该值赋给组件。

<select 
value={props.selectedCountry} 
onChange={props.onChange("country")}
...otherProps
>
{props.countries.map(country => (
<option value ={country}>{country}</option>
))}
</select>

相关内容

最新更新