ReactJS:功能组件和类组件之间有什么区别 [英] ReactJS: what is the difference between functional component and class component
问题描述
任何人都可以详细解释ReactJS中功能组件和类组件之间的区别吗?
Could anyone can explain in detail the difference between functional component and class component in ReactJS?
当我们使用功能组件时以及何时使用类组件? / p>
When we use a functional component and when we use the class component?
推荐答案
这是伟大的文章,演示和容器组件,由Dan Abramov为您提供帮助。
Here's a great article, "Presentational and Container Components", by Dan Abramov that can help you with that.
这是我理解这一点的 tl; dr; :
-
你会必须使用
类CreatePostForm扩展Component {}
或React.createClass()
if:
- 您需要访问组件的生命周期方法 (即:componentWillMount或componentDidMount) -
注意:自 React 16.8 ,这不再是必然的,我强烈建议您阅读 React Hooks 一旦你熟悉它们,它们就可以使事情变得更简单; - 你的组件直接访问你的商店,因此保持状态(有些人也称这种组件,智能组件或容器。)
- you need access to your component's lifecycle methods (ie.: componentWillMount or componentDidMount) – NOTE: Since React 16.8, this is no longer necessarily true and I would highly recommend reading on React Hooks as they can makes things simpler once you get comfortable with them;
- your component have direct access to your store and thus holds state (some people also call this kind of components, smart components or containers).
当你的组件只接收道具并渲染它们时到页面,然后你有一个'无状态组件'(有些人称这些组件为哑组件或表示组件),并且可以使用纯函数来表示它,它可以像这样简单
When your component just receive props and render them to the page, then you have a 'stateless component' (some people call these components dumb components or presentational components) and can use a pure function to represent it and it can be as simple as this
import来自'react'的React;
export default()=> < p>来自React的问候!< / p> ;;
现在,重要的是要记住纯函数可能比这更复杂,如果你对一些ESNext语法和解构和传播属性感到满意,你可以有一个如下所示的表示组件:
Now, it's important to remember that a pure function can get way more complex than this and if you're comfortable with some ESNext syntax and destructuring and spreading attributes, you can have a presentational component that looks like this:
import React from 'react';
import AnotherComponent from './AnotherComponent';
export default ({ children, ...rest }) =>
<AnotherComponent extraProp="anExtraProp" { ...rest }>
{ children }
</AnotherComponent>;
希望这有帮助。
这篇关于ReactJS:功能组件和类组件之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!