What's the different between
var MyClass = React.createClass({...});
To
class MyClass extends React.Component{...}
As of React 15.5, createClass is deprecated. You'll get warnings in the console if you're using it in your code – and, when React 16 comes out, createClass will be removed entirely.
React. createClass allows you to generate component "classes." Under the hood, your component class is using a bespoke class system implemented by React. With ES6, React allows you to implement component classes that use ES6 JavaScript classes.
Using the extends keyword, you can allow the current component to access all the component's properties, including the function, and trigger it from the child component. This example creates one component called ParentClass. jsx. ParentClass extends the component from React as React.
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.
These two ways depend on if you are using ES6 syntax or not, and they also change the way you set up your initial state.
When using ES6 classes, You should initialize state in the constructor
.
When using React.createClass you have to use the getInitialState
function.
ES6 Class Syntax:
class MyComponent extends React.Component { constructor(props) { super(props); this.state = { /* initial state, this is ES6 syntax (classes) */ }; } }
ES5 React.CreateClass syntax:
var MyComponent = React.createClass({ getInitialState() { return { /* initial state */ }; }, });
These will both work the same way to set up initial state.
With the class MyClass extends React.Component{...}
syntax,
you can not use mixins and you need to bind the context of the method yourself
class MyClass extends Component { constructor() { super(); this.handleClick.bind(this); } handleClick() { this.setState(...); } }
to me these are the biggest differences.
to replace the mixin, you can use a Container to wrap your component
export default Container(MyClass); function Container(Component) { var origin = Component.prototype.componentDidMount; Component.prototype.componentDidMount = function() { origin.apply(this, arguments); /* do mixin */ } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With