javascript - 请教一下 react 用es5 和es6写的下面的demo 为何 ES6的代码不能运行
PHP中文网
PHP中文网 2017-04-11 10:33:52
[JavaScript讨论组]

注:代码都是经过转化后可以执行的
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 (
                <p>
                    <p onClick={this.clearAndFocusInput}>
                        Click to Focus and Reset
                    </p>
                    <input
                        ref="theInput"
                        value={this.state.userInput}
                        onChange={this.handleChange}
                    />
                </p>
            );
        }
}

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 (
        <p>
          <p onClick={this.clearAndFocusInput}>
            Click to Focus and Reset
          </p>
          <input
            ref="theInput"
            value={this.state.userInput}
            onChange={this.handleChange}
          />
        </p>
      );
    }
  });
PHP中文网
PHP中文网

认证0级讲师

全部回复(3)
迷茫

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

伊谢尔伦

浏览器不一定支持 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)}/>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号