React.createClass vs extends Component

前端 未结 4 784
长发绾君心
长发绾君心 2020-12-13 03:40

What\'s the different between

var MyClass = React.createClass({...});

To

class MyClass extends React.Component{...}
         


        
4条回答
  •  抹茶落季
    2020-12-13 04:13

    React.createClass

    Here we have a const with a React class assigned, with the important render function following on to complete a typical base component definition.

    import React from 'react';
    
    const Contacts = React.createClass({
        render() {
        return (
        
    ); } }); export default Contacts;

    React.Component

    Let’s take the above React.createClass definition and convert it to use an ES6 class.

    import React from 'react';
    
    class Contacts extends React.Component {
      constructor(props) {
      super(props);
      }
        render() {
        return (
        
    ); } } export default Contacts;

    From a JavaScript perspective we’re now using ES6 classes, typically this would be used with something like Babel to compile the ES6 to ES5 to work in other browsers. With this change, we introduce the constructor, where we need to call super() to pass the props to React.Component.

    For the React changes, we now create a class called “Contacts” and extend from React.Component instead of accessing React.createClass directly, which uses less React boilerplate and more JavaScript. This is an important change to note further changes this syntax swap brings.

    More

提交回复
热议问题