我可以传递props
与扩展运算符。即,
<Component x={props.x} y={props.y} />
等于:
<Component {...props} />
我们可以在同名的组件定义中使用它。
我的问题是如何传递这样的函数?下面的等效代码是什么?
<Component handleClick = {this.handleClick}
anotherHandleClick = {this.anotherHandleClick}/>
编辑:
上面一行将传递函数handleClick
和anotherHandleClick
给 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.
这是上述两者的工作示例,请查看:
关于reactjs - React 中传递同名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46909870/