reactjs - React 中传递同名函数

标签 reactjs react-props

我可以传递props与扩展运算符。即,

<Component x={props.x} y={props.y} />

等于:

<Component {...props} />

我们可以在同名的组件定义中使用它。

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

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

编辑:

上面一行将传递函数handleClickanotherHandleClick给 child 。有类似<Component {...Fns} />的东西吗?这样每个函数都会作为同名的 props 传递下去。

最佳答案

是的,你可以这样做:

1)第一种方式:

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

2)第二种方式:

不使用任何额外的变量constmethods = {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

关于reactjs - React 中传递同名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46909870/

相关文章:

javascript - 通过接收 Prop 数据获取默认状态值 - React

javascript - ReactJS:在模糊而不是每次击键时保存输入值

javascript - React Hooks - 更改父样式以反射(reflect)子 onClick

javascript - removeEventListener 不适用于 Modal 关闭

javascript - ES6 数组映射不返回任何内容 : ReactJS

javascript - Redux 没有以我可以使用对象的方式将状态映射到 props

reactjs - 在 typescript 中将 useState 作为 props 传递

javascript - 在 React 中将 Props 映射到数组

ios - 似乎您正在尝试从 'ReactNative.Component' 包访问 'react-native'

javascript - 如何防止模态点击?