Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

javascript - ReactJS: what is the difference between functional component and class component

Could anyone can explain in detail the difference between functional component and class component in ReactJS?

When we use a functional component and when we use the class component?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's a great article, "Presentational and Container Components", by Dan Abramov that can help you with that.

And here's a tl;dr; of the way I understand this:

  1. You'll have to use class CreatePostForm extends Component {} or React.createClass() if:

    • 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 make things simpler once you get comfortable with them;
    • your component have direct access to your store and thus holds state (some people also call these components: smart components or containers).
  2. 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 from 'react'; export default () => <p>Hello from React!</p>;

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>;

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...