简体   繁体   English

从子类ReactJS向父类中的事件处理程序传递参数

[英]Passing a parameter to an event handler in the parent class from a child class ReactJS

I am trying to pass a parameter to an event handler in a parent class, but am having some difficulty. 我正在尝试将参数传递给父类中的事件处理程序,但是遇到了一些困难。 I have done a good amount of research and am close to answer, but something's not quite working. 我已经做了大量的研究,并且很容易回答,但是有些事情做得不太好。 Below I will give a basic hypothetical example of what I would like to do that doesn't work. 下面,我将给出一个基本的假设示例,说明我想这样做是行不通的。

class Parent extends React.Component {
       constructor(props){
           super(props);
           this.handleClick = this.handleClick.bind(this);
       }

       handleClick(i){
           return event => console.log(i);
       }

       render(){
          return <Child onClick={this.handleClick}></button>;
       }
}

class Child extends React.Component {
       render() {
            const myVar = 2;
            return <button onClick={this.props.onClick(myVar)}></button>;
       }
}

I know the onClick prop that is passed to the Child is not a function, so I am unable to pass parameters directly to it. 我知道传递给Child的onClick道具不是函数,因此我无法直接将参数传递给它。 What is the best way to go about doing this? 这样做的最佳方法是什么? Thanks for you help! 感谢您的帮助!

Make the following update to your code 对您的代码进行以下更新

class Child extends React.Component{
       render(){
            const var = 2;
            return <button onClick={ () => {this.props.onClick(var)} }</button>;
       }
}

Furthermore, you should refactor the following method used by parent as so. 此外,您应该这样重构父级使用的以下方法。 You are passing e needlessly. 你逝去的e不必要。

handleClick(i){
    console.log(i);
}

The onClick on your child component was immediately invoked instead of waiting for the onClick event to fire. 您的子组件上的onClick被立即调用,而不是等待onClick事件触发。

You can't do 你做不到

handleClick(i){
           return (e => {console.log(i)});
       }

instead, try 相反,尝试

handleClick(i){
          console.log(i)
       }

and move the event handling to where it is being called. 并将事件处理移至被调用的位置。 So instead of 所以代替

<button onClick={this.props.onClick(var)}</button>

You want to try 你想尝试

<button onClick={e => this.props.onClick(var)}</button>

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

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