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

前端之家收集整理的这篇文章主要介绍了reactjs – 在React中传递一个具有相同名称的函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以通过传播操作符传递道具.即
<Component x={props.x} y={props.y} />

等于:

<Component {...props} />

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

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

<Component handleClick = {this.handleClick} 
   anotherHandleClick = {this.anotherHandleClick}/>

编辑:

上面的行将传递函数handleClick和anotherHandleClick传递给子节点.是否有类似< Component {... Fns} />这样每个函数都会作为具有相同名称的道具传递下去.

是的,你可以这样做:

1)第一种方式:

render() {
   const methods = { handleClick : this.handleClick };
   return(
        <Component {...methods} />
   )
}

2)第二种方式:

不使用任何额外的varible const方法= {handleClick:this.handleClick};

render() {
    return(
        <Component {...this.constructor.prototype} />
        // or
        <Component {...this.__proto__} />
    )
}

NOTE : The second method is not preferable as it gives all the access
of class to a child,all means all,constructor,render everything….

I just want to show the ways we can achieve,still if there are lots
of functions we can go with second way too,but be careful with that.

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

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

原文链接:https://www.f2er.com/react/300829.html

猜你在找的React相关文章