gpt4 book ai didi

reactjs - 如何在 React es6 组件中定义静态?

转载 作者:行者123 更新时间:2023-12-01 16:03:46 26 4
gpt4 key购买 nike

我想在 React es6 组件中定义静态。我知道下面的组件是如何完成的

var MyComponent = React.createClass({
statics: {
customMethod: function(foo) {
return foo === 'bar';
}
},
render: function() {
}
});

但希望定义如下的 react 组件相同

class MyComponent extends Component{ ... }

此外,我想从 MyComponent 将被实例化的地方调用该方法。

最佳答案

您可以使用static关键字在 ES6 类中创建静态成员变量:

class StaticMethodCall {
static staticMethod() {
return 'Static method has been called';
}
static anotherStaticMethod() {
return this.staticMethod() + ' from another static method';
}
}
StaticMethodCall.staticMethod();
// 'Static method has been called'

StaticMethodCall.anotherStaticMethod();
// 'Static method has been called from another static method'

Source and more info on MDN

关于reactjs - 如何在 React es6 组件中定义静态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38381974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com