[英]When should a react component be declared as a function, and not a class?
我不确定何时将反应组件声明为简单的独立函数,而不是常规class myComponent extends Component
语法。 要使用React的文档(位于此处 )中的示例:
以下称为“组件”
function BoilingVerdict(props) {
if (props.celsius >= 100) {
return <p>The water would boil.</p>;
}
return <p>The water would not boil.</p>;
}
虽然它似乎只是一个函数,并被声明为任何常规的旧函数。 然后在下一段中,以下内容也被定义为组件,看起来更像我认为组件应该看起来的样子:
class Calculator extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {temperature: ''};
}
handleChange(e) {
this.setState({temperature: e.target.value});
}
render() {
const temperature = this.state.temperature;
return (
<fieldset>
<legend>Enter temperature in Celsius:</legend>
<input
value={temperature}
onChange={this.handleChange} />
<BoilingVerdict
celsius={parseFloat(temperature)} />
</fieldset>
);
}
}
这两个“组件”有什么区别? 如果第一个示例不是从Component类继承而且没有使用React.createClass
创建, React.createClass
第一个示例实际上是一个组件吗? 我很感激有人解释这种区别,因为我无法在文档的任何地方找到答案。
如果不需要使用生命周期方法且组件不具有状态,则可以将组件声明为函数。 如果组件是扩展Component
的类,则只能使用componentWillMount()
和componentDidMount()
等组件生命周期方法。
Facebook有两个互补的文档很好地解释了这一点:
https://facebook.github.io/react/docs/components-and-props.html https://facebook.github.io/react/docs/state-and-lifecycle.html
TL; DR“组件”主要负责表示某些DOM。 根据应用程序的组织方式,组件可能需要也可能不需要维护自己的状态,也无需访问componentDidMount
或render
等生命周期方法。 如果您确实需要这些功能,那么您的组件应该是一个继承自React.Component
的类。 否则,您可能会将组件编写为普通的旧函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.