简体   繁体   English

如何在ReactJS中使用参数正确调用父组件中的事件处理函数?

[英]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: 在此组件的render方法中,我将此函数传递给子组件,如下所示:

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

In the FilterGroupsSection (child) component, I am trying to call this function like so: 在FilterGroupsSection(子组件)组件中,我试图这样调用此函数:

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. 您有2个选择。 Just remove additional {} in function binding to your child component or use return: 只需删除绑定到您的子组件的函数中的其他{}或使用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. 否则, 未命名的内联函数和对象将具有新的引用,并触发下面的组件树的完全重新呈现。

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

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