简体   繁体   中英

How to correctly call an event handler function in a parent component with a parameter in ReactJS?

I have a function in a component which I want to call in a child component.

This is the function in the parent component:

handleFilterGroupsQuery = queryObject => {
    return queryObject;
}

I have binded it to this in the constructor (in parent component):

constructor(props) {
    super(props);
    this.handleFilterGroupsQuery = this.handleFilterGroupsQuery.bind(this);
}

Within the render method of this component, I am passing down this function to a child component like so:

<FilterGroupsSection 
    handleFilterGroupsQuery={(queryObject) => {this.handleFilterGroupsQuery(queryObject)}} 
/>

In the FilterGroupsSection (child) component, I am trying to call this function like so:

let test = 'test'
console.log(this.props.handleFilterGroupsQuery(test));

This displays 'undefined' in the console. I can't figure out why the parameter value is not being passed correctly.

Appreciate any advice.

You have 2 options. Just remove additional {} in function binding to your child component or use return:

 handleFilterGroupsQuery={(queryObject) => this.handleFilterGroupsQuery(queryObject)}

or

 handleFilterGroupsQuery={(queryObject) => { return this.handleFilterGroupsQuery(queryObject)}}

One good solution would be to pass the argument and the function separately:

<Parent 
  handleFilterGroupsQuery={this.handleFilterGroupsQuery}
  queryObject={queryObject}
/>

Then, you can easily bind the argument every time you call the function at your child component:

this.props.handleFilterGroupsQuery.bind(null, queryObject); 

Otherwise, the unnamed inline functions and object will have new references and trigger a complete re-render of the component tree below.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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