假设我定义了一个这样的组件:
const myComponent = class MyComponent extends React.Component {}
Run Code Online (Sandbox Code Playgroud)
后来我想向定义的组件添加一个构造函数,如下所示:
myComponent.constructor = function(props) {
super(props)
this.state = { hello: 'world' }
}
Run Code Online (Sandbox Code Playgroud)
有谁知道这是否可能?如果是这样,有没有人知道与上述相比在实现上有什么不同?谢谢!
您不能覆盖 es6 类的构造函数。您可以使用 es5 类来完成此操作,因此它可以与 babel 一起工作(并且很脆弱)。
对于其他方法,你会这样做
MyComponent.prototype.methodName = function() {}
Run Code Online (Sandbox Code Playgroud)
在我看来,这是一个缺失的功能,因为它将允许更好的依赖注入。
如果 TC39 偶然发现这个页面,我希望有 Reflect.setConstructor。
| 归档时间: |
|
| 查看次数: |
2008 次 |
| 最近记录: |