我见过这样的代码
function abc(){
return 'abc'
}
class MyComponent extends React.Component {
static abc = abc;
render() { return <h1>{this.abc}</h1>; }
}
其中函数 abc
是在 React 类之外定义的。我不知道作者为什么那样做,为什么不能在类里面做?
最佳答案
这些是 ES6 static methods并且不是 React 独有的。它们是组件类的成员,而不是组件实例的成员。它们在 React 中没有被广泛使用,但它们很有用。它甚至在 React docs 中被提及:
Sometimes it’s useful to define a static method on a React component. For example, Relay containers expose a static method getFragment to facilitate the composition of GraphQL fragments.
它们可以用作组件的公共(public)成员,由组件的所有实例共享。给你个思路,其他static members of a React class是 displayName
和 defaultProps
。
另见 Static methods in React .如您所见,使用静态方法的情况并不多。
关于javascript - 在 React 组件的类之外编写函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47668144/