简体   繁体   中英

When creating React components should I use functional components, React.createClass or extends React.Component?

I am quite new to React and have been reading up a lot about it. I have come across three different methods to create components:

Functional Components:

const Hello = ({world}) => {
  return (
    <div>{"Hello" + world}</div>
  );     
}

React.createClass (Factory):

const Hello = React.createClass({
  render: function() {
    return <div>{"Hello" + this.props.world}</div>
  }
});

ES6 Class Extends

class Hello extends React.Component {
  render() {
    return (
      <div>{"Hello" + this.props.world}</div>
    );
  }
}

Apart from the obvious that the functional components don't have any state coupled to it and is probably a more functional approach to doing components, why would I use the different methods?

In the React documentation they use all three methods. Some of the Stack Overflow articles suggest the Class method and then some suggest the Factory method.

Using functional is recommended for components that are stateless.

Using React.Component extend is recommended if you are working with ES6+/TypeScript code. React Native has support only for this type of component creation.

React.createClass is for used with ES5.

Browsers will soon have a complete support and Facebook recommends to use React.Component instead of React.createClass and to use functional for stateless .

Edit

Facebook added a deprecation warning to React.createClass in React 15.6.0 and points users to use create-react-class instead.

As I know, it is recommend to use functional component when you need just create presentational logic component . For component that has any logic we use smth like React.createClass() .

There are two ways of doing that:

First , you create general component and than divide it on presentational logic and business logic.

Second , you can create them alongside.

Be careful! When divide these components, your business logic must render your presentational logic!

For more practice see tutorials on the codecademy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM