如何在ES6中编写React教程(ES2015)

时间:2016-01-21 18:52:10

标签: javascript reactjs

我正在重写ES6中的Update 1,并陷入了tutorial16.js。什么是以es6格式编写es5的正确方法?

// tutorial16.js
var CommentForm = React.createClass({
  getInitialState: function() {
    return {author: '', text: ''};
  },
  handleAuthorChange: function(e) {
    this.setState({author: e.target.value});
  },
  handleTextChange: function(e) {
    this.setState({text: e.target.value});
  },
  render: function() {
    return (
      <form className="commentForm">
        <input
          type="text"
          placeholder="Your name"
          value={this.state.author}
          onChange={this.handleAuthorChange}
        />
        <input
          type="text"
          placeholder="Say something..."
          value={this.state.text}
          onChange={this.handleTextChange}
        />
        <input type="submit" value="Post" />
      </form>
    );
  }
});

这是我在ES6中写的CommentForm.jsx。如果我尝试在表单中键入任何内容,我会在控制台中收到此消息: Uncaught TypeError:无法读取属性&#39; setState&#39;未定义的 我做错了什么?

import React from 'react';

class CommentForm extends React.Component {

    constructor(props){
        super(props);
        this.state = { author: '', text: '' }
    }

    handleAuthorChange(e){
        this.setState({author: e.target.value});
    };

    handleTextChange(e){
        this.setState({text: e.target.value});
    }

    render(){
        return(
            <form className="commentForm">
                <input type="text" placeholder="Your name" value={this.state.author} onChange={this.handleAuthorChange}/>
                <input type="text" placeholder="Say something..." value={this.state.text} onChange={this.handleTextChange}/>
                <input type="submit" value="Post" />
            </form>
        );
    }
}

export default CommentForm;

2 个答案:

答案 0 :(得分:1)

您缺少对实例的绑定onChange处理程序。他们在完全不同的情况下被解雇,this并未指向CommentForm

应该是:

<input onChange={this.handleAuthorChange.bind(this)} type="text" placeholder="Your name" value={this.state.author} />
<input onChange={this.handleTextChange.bind(this)} type="text" placeholder="Say something..." value={this.state.text} />

答案 1 :(得分:0)

使用属性初始值设定项(ES6 +),它可能如下所示:

class CommentForm extends React.Component {

    state = {
        author: '', text: ''
    };

    handleAuthorChange = (e) => {
        this.setState({author: e.target.value});
    };

    handleTextChange = (e) => {
        this.setState({text: e.target.value});
    };

    render() {
        return <form className="commentForm">
            <input
                type="text"
                placeholder="Your name"
                value={this.state.author}
                onChange={this.handleAuthorChange}
            />
            <input
                type="text"
                placeholder="Say something..."
                value={this.state.text}
                onChange={this.handleTextChange}
            />
            <input type="submit" value="Post" />
        </form>
    }
}