在 React 中传递同名函数
Pass down a function with same name in React
我可以用扩展运算符传递 props
。即,
<Component x={props.x} y={props.y} />
等于:
<Component {...props} />
并且我们可以在同名的组件定义中使用它。
我的问题是如何传递这样的函数?下面的等效代码是什么?
<Component handleClick = {this.handleClick}
anotherHandleClick = {this.anotherHandleClick}/>
编辑:
上一行会将函数 handleClick
和 anotherHandleClick
传递给 child。是否有类似 <Component {...Fns} />
的东西,以便每个函数都将作为具有相同名称的道具传递下去。
是的,您可以这样做:
1) 第一种方式:
render() {
const methods = { handleClick : this.handleClick };
return(
<Component {...methods} />
)
}
2) 第二种方式:
不使用任何额外变量const methods = { 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.
这是上面两个的工作示例,请看一下:
我可以用扩展运算符传递 props
。即,
<Component x={props.x} y={props.y} />
等于:
<Component {...props} />
并且我们可以在同名的组件定义中使用它。
我的问题是如何传递这样的函数?下面的等效代码是什么?
<Component handleClick = {this.handleClick}
anotherHandleClick = {this.anotherHandleClick}/>
编辑:
上一行会将函数 handleClick
和 anotherHandleClick
传递给 child。是否有类似 <Component {...Fns} />
的东西,以便每个函数都将作为具有相同名称的道具传递下去。
是的,您可以这样做:
1) 第一种方式:
render() {
const methods = { handleClick : this.handleClick };
return(
<Component {...methods} />
)
}
2) 第二种方式:
不使用任何额外变量const methods = { 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.
这是上面两个的工作示例,请看一下: