与 ES5 相比,React 的 ES6 语法有何不同?

1.require 与 import

1
2
3
4
5
// ES5
var React = require('react');
  
// ES6
import React from 'react';

2.export 与 exports

1
2
3
4
5
// ES5
module.exports = Component;
  
// ES6
export default Component;

3.component 和 function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ES5
var MyComponent = React.createClass({
    render: function() {
        return
            <h3>Hello Edureka!</h3>;
    }
});
  
// ES6
class MyComponent extends React.Component {
    render() {
        return
            <h3>Hello Edureka!</h3>;
    }
}

4.props

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// ES5
var App = React.createClass({
    propTypes: { name: React.PropTypes.string },
    render: function() {
        return
            <h3>Hello, {this.props.name}!</h3>;
    }
});
 
// ES6
class App extends React.Component {
    render() {
        return
            <h3>Hello, {this.props.name}!</h3>;
    }
}

5.state

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// ES5
var App = React.createClass({
    getInitialState: function() {
        return { name: 'world' };
    },
    render: function() {
        return
            <h3>Hello, {this.state.name}!</h3>;
    }
});
 
// ES6
class App extends React.Component {
    constructor() {
        super();
        this.state = { name: 'world' };
    }
    render() {
        return
            <h3>Hello, {this.state.name}!</h3>;
    }
}

 

posted on 2021-12-20 13:50  呗儿  阅读(67)  评论(0编辑  收藏  举报

导航