[关闭]
@gongzhen 2016-07-22T03:14:46.000000Z 字数 2048 阅读 6278

ES5与ES6语法区别

react


创建组件

  1. //es5
  2. var MyComponent = React.createClass({
  3. render: function() {
  4. return (
  5. <div></>
  6. );
  7. }
  8. });
  9. module.exports = MyComponent;
  10. //es6
  11. class MyComponent extends React.Component {
  12. render() {
  13. return (
  14. <div></>
  15. );
  16. }
  17. }
  18. export MyComponent Apply;

getInitialState & constructor

es6中没有getInitialState方法,设置state用constructor

  1. //es5
  2. getInitialState: function() {
  3. return {
  4. speakersKey: 'shanghai'
  5. };
  6. },
  7. //es6
  8. constructor(props) {
  9. super(props);
  10. this.state = {
  11. speakersKey: 'shanghai'
  12. };
  13. }

es6成员之间无逗号

  1. //es5
  2. getInitialState: function() {
  3. return {
  4. speakersKey: 'shanghai'
  5. };
  6. },
  7. onTabItemSelectedChanged: function(item, index) {
  8. this.setState({
  9. speakersKey: item.key
  10. });
  11. },//以逗号结尾
  12. render: function() {
  13. return (
  14. <div></>
  15. );
  16. }
  17. //es6
  18. constructor(props) {
  19. super(props);
  20. this.state = {
  21. busy: false
  22. };
  23. }
  24. render() {
  25. return (
  26. <div></>
  27. );
  28. }//结尾没有逗号
  29. onClickForumItem(forum, index, forums, event) {
  30. forum.selected = !(forum.selected);
  31. event.currentTarget.className = forum.selected ? 'selected' : '';
  32. }

绑定事件

es6绑定事件时需要显示调用bind()方法设置组件上下文,es5不需要

  1. //es5
  2. <div onClick={this.onItemClick}></div>
  3. //es6
  4. <div onClick={this.onItemClick.bind(this)}></div>

传递事件参数

React里的事件参数传递和传统的JS参数有些不一样,需要通过bind方法来绑定参数,第一个参数指向this,第二个参数开始才是事件函数接收到的参数:

  1. <button onClick={this.handleClick.bind(this, props0, props1, ...}></button>
  2. handleClick(porps0, props1, ..., event) {
  3. // your code here
  4. }

我们使用bind(this)显式的绑定了事件处理函数的运行上下文,当使用ES6 Class语法定义组件时,必须使用bind(this)显式的绑定事件处理函数的运行上下文

完整示例

  1. //es5
  2. require('./MyComponent.styl');
  3. var React = require('react');
  4. var MyComponent = React.createClass({
  5. getInitialState: function() {
  6. return {
  7. title: 'hi'
  8. };
  9. },
  10. onClickTitle: function() {
  11. this.setState({
  12. title: 'Hello'
  13. });
  14. },
  15. render: function() {
  16. return (
  17. <div className="my-component">
  18. <h1 onclick={this.onClickTitle}> {this.state.title} </h1>
  19. </div>
  20. );
  21. }
  22. });
  23. module.exports = MyComponent;
  24. //es6
  25. import './MyComponent.styl';
  26. import React from 'react';
  27. class MyComponent extends React.Component {
  28. constructor(props) {
  29. super(props);
  30. this.state = {
  31. title: 'hi'
  32. };
  33. }
  34. onClickTitle() {
  35. this.setState({
  36. title: 'Hello'
  37. });
  38. }
  39. render() {
  40. return (
  41. <div className="my-component">
  42. <h1 onclick={this.onClickTitle.bind(this)}> {this.state.title} </h1>
  43. </div>
  44. );
  45. }
  46. }
  47. export default MyComponent;
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注