首页 > 请教一下 react 用es5 和es6写的下面的demo 为何 ES6的代码不能运行

请教一下 react 用es5 和es6写的下面的demo 为何 ES6的代码不能运行

注:代码都是经过转化后可以执行的
ES6 DEMO

class App extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
            userInput: ''
        }
    }
    handleChange(e) {
        this.setState({userInput: e.target.value});
    }
    clearAndFocusInput() {
        this.setState({userInput: ''}, function() {
            this.refs.theInput.getDOMNode().focus();   // Boom! Focused!
        });
    }
    render() {
            return (
                <div>
                    <div onClick={this.clearAndFocusInput}>
                        Click to Focus and Reset
                    </div>
                    <input
                        ref="theInput"
                        value={this.state.userInput}
                        onChange={this.handleChange}
                    />
                </div>
            );
        }
}

ES5 DEMO

  var App = React.createClass({
    getInitialState: function() {
      return {userInput: ''};
    },
    handleChange: function(e) {
      this.setState({userInput: e.target.value});
    },
    clearAndFocusInput: function() {
      // Clear the input
      this.setState({userInput: ''}, function() {
        // This code executes after the component is re-rendered
        this.refs.theInput.getDOMNode().focus();   // Boom! Focused!
      });
    },
    render: function() {
      return (
        <div>
          <div onClick={this.clearAndFocusInput}>
            Click to Focus and Reset
          </div>
          <input
            ref="theInput"
            value={this.state.userInput}
            onChange={this.handleChange}
          />
        </div>
      );
    }
  });

浏览器不一定支持 ES6 ,所以下载个 babel 把 ES6 「翻译」成 ES5 就好了


这是在 ES6 中作用域的问题, 你可以将操作函数在 constructor 中绑定 this

constructor(props) {
        super(props);
        this.state = {
            userInput: ''
        }
        this.handleChange = this.handleChange
        this.clearAndFocusInput = this.clearAndFocusInput.bind(this)
    }

在 stage-0 也可以通过箭头函数定义 handleChange:

  handleChange = () => {
  }

另外在传递属性的时候也可以:

<input onChange={this.handleChange.bind(this)}/>

ES6的代码是需要预处理一下的,可以用babel

【热门文章】
【热门文章】