首页 > 解决方案 > React:组件构造函数可以有多个参数吗?

问题描述

只是好奇组件构造函数可以有多个参数吗?

从:

constructor(props) {
    super(props)
}

进入:

constructor(props, parent) {
    super(props)
    this.parent = parent;
}

所以父组件可以this.parent在子组件内部分配。

例如这是父组件要初始化子组件:

constructor(props) {
    super(props)
    this.helpers = new Child(<i_am_not_sure_here>, this);
}

标签: reactjsreact-native

解决方案


通常,在 React 中构造函数仅用于两个目的:

  • 通过将对象分配给 this.state 来初始化本地状态。
  • 将事件处理程序方法绑定到实例。

查看官方文档了解更多信息:

https://reactjs.org/docs/react-component.html#constructor


推荐阅读