在React中传递一个具有相同名称的函数

Asi*_*K T 7 reactjs react-props

我可以props使用传播运算符进行传递.即

<Component x={props.x} y={props.y} />
Run Code Online (Sandbox Code Playgroud)

等于:

<Component {...props} />
Run Code Online (Sandbox Code Playgroud)

我们可以在具有相同名称的组件定义中使用它.

我的问题是如何传递这样的函数?下面的等效代码是什么?

<Component handleClick = {this.handleClick} 
   anotherHandleClick = {this.anotherHandleClick}/>
Run Code Online (Sandbox Code Playgroud)

编辑:

上面的行将向下传递函数handleClickanotherHandleClick传递给孩子.有没有这样的东西<Component {...Fns} />,每个函数将作为具有相同名称的道具传递.

Viv*_*shi 7

是的,你可以这样做:

1)第一种方式:

render() {
   const methods = { handleClick : this.handleClick };
   return(
        <Component {...methods} />
   )
}
Run Code Online (Sandbox Code Playgroud)

2)第二种方式:

不使用任何额外的变量 const methods = { handleClick : this.handleClick };

render() {
    return(
        <Component {...this.constructor.prototype} />
        // or
        <Component {...this.__proto__} />
    )
}
Run Code Online (Sandbox Code Playgroud)

注意:第二种方法不是优选的,因为它给了孩子所有类的访问权,所有意味着所有,构造函数,渲染一切....

我只想展示我们可以实现的方法,如果有很多功能我们也可以采用第二种方式,但要小心.


以下是上述两个工作示例,请看一下:

https://stackblitz.com/edit/react-parent-click-prop