在反应组件中的 class 之外编写函数
writing function outside of a class in react component
我见过这样的代码
function abc(){
return 'abc'
}
class MyComponent extends React.Component {
static abc = abc;
render() { return <h1>{this.abc}</h1>; }
}
其中函数 abc
是在反应 class 之外定义的。我不知道作者为什么那样做,为什么不能在 class?
内做
这些是ES6 static methods and are not exclusive to React. They are members of the component class and not of instances of the component. They are not used extensively in React, but they can be useful. It is even mentioned in the 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.
它们可以用作组件的公共成员,由组件的所有实例共享。为了给你一个想法,其他 static members of a React class 是 displayName
和 defaultProps
。
另见 。如您所见,使用静态方法的情况并不多。
import React, { Component } from 'react';
class Contacts extends Component {
render() {
return (
Contact()
);
}
}
const Contact = () => {
return (
<div>
<p>Contactssssss</p>
</div>
);
};
export default Contacts;
一方面,在 class 之外声明函数更容易导出。这在测试您的 React 应用程序时非常有用,即通过玩笑。
我见过这样的代码
function abc(){
return 'abc'
}
class MyComponent extends React.Component {
static abc = abc;
render() { return <h1>{this.abc}</h1>; }
}
其中函数 abc
是在反应 class 之外定义的。我不知道作者为什么那样做,为什么不能在 class?
这些是ES6 static methods and are not exclusive to React. They are members of the component class and not of instances of the component. They are not used extensively in React, but they can be useful. It is even mentioned in the 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.
它们可以用作组件的公共成员,由组件的所有实例共享。为了给你一个想法,其他 static members of a React class 是 displayName
和 defaultProps
。
另见
import React, { Component } from 'react';
class Contacts extends Component {
render() {
return (
Contact()
);
}
}
const Contact = () => {
return (
<div>
<p>Contactssssss</p>
</div>
);
};
export default Contacts;
一方面,在 class 之外声明函数更容易导出。这在测试您的 React 应用程序时非常有用,即通过玩笑。