简体   繁体   English

在子组件上运行 function 并在父组件上调用 function

[英]Run a function on child component and call a function on parent component

I want to get the states from a country on change and pass handleChange to parent so on Child component i'm rendering the following:我想从一个国家的变化中获取状态并将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>

I'm passing handleChange to parent which looks as follows我将handleChange传递给父级,如下所示

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

my question is how can I run a function on the child component that gets data(the states that below to that country ) and still pass handleChange('country') to parent我的问题是如何在获取数据的子组件上运行 function 并仍然将 handleChange('country') 传递给父组件

You never pass anything up the component tree in react.你永远不会在组件树中传递任何东西。 It's one of the core principles of react.这是 React 的核心原则之一。 If you want to have access to something in both parent and child then define it in the parent and pass it down to the child.如果您想同时访问父级和子级中的某些内容,请在父级中定义它并将其传递给子级。 So define the state and the logic (so state.countries and handleChange) in the parent and pass both as props to the child component.因此,在父组件中定义 state 和逻辑(因此 state.countries 和 handleChange)并将两者作为道具传递给子组件。

EDIT: Have to respond to your comment here, comments are too small.编辑:必须在这里回复您的评论,评论太少了。

You would need to know which country is currently selected, yes, but you save that info in the state as well and update it inside your handler.您需要知道当前选择了哪个国家,是的,但是您将该信息也保存在 state 中并在您的处理程序中更新它。 So your state would look something like所以你的 state 看起来像

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

And inside your handleChange function you set the country prop to whatever the value of the option was so your parent has access to which option was selected through this.state.country.在您的 handleChange function 中,您将 country 属性设置为选项的任何值,以便您的父母可以访问通过 this.state.country 选择的选项。 If you pass this.state.country to your child component throught props then you can give that value to the component via the value prop.如果您将 this.state.country 通过道具传递给您的子组件,那么您可以通过 value 道具将该值赋予组件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM