React costructor不起作用

时间:2016-03-31 07:23:42

标签: reactjs

考虑这个反应类

var sentence = "The FBI has managed to unlock the iPhone";

define(["./UserInput","./Statistic","./RandomWords","react", "react-dom"],
  (UserInput,Statistic,RandomWords,React, ReactDOM) => {

      var Root = React.createClass({
        constructor() {
            super();
            console.log("Hey");
            this.state={sentenct: sentence }

          }

    render: function() {
          return (
            <div >

                <h1>Welcome to our game</h1>
                <UserInput/>
                <RandomWords NewWord={ sentence }/>
                <Statistic   speed={"Salman"}  success={"saba"} />
            </div>
          );
        }
      });

      ReactDOM.render(
        React.createElement(Root, null),
        document.getElementById('content')
      );
});

我试过this,然后 我做了一个costructor,我希望看到&#34;嘿&#34;在我的控制台中却没有发生?

2 个答案:

答案 0 :(得分:0)

您必须使用this.state.sentence而不是变量

var sentence = "The FBI has managed to unlock the iPhone";

    render: function() {
              return (
                <div >

                    <h1>Welcome to our game</h1>
                    <UserInput/>
                    <RandomWords NewWord={ this.state.sentence }/>
                    <Statistic   speed={"Salman"}  success={"saba"} />
                </div>
              );
    }

并且ReactDOM不需要元素,但是类

ReactDOM.render(<Root />, document.getElementById('content'));

如果问题仍然存在,请在下面的评论部分写下,愿意调查

答案 1 :(得分:0)

React.createClass创建的类没有constructor方法。 只有ES6课程有constuctor方法。

示例:

class Root extends React.Component {
    constructor() {
        super();
        console.log("Hey");
        this.state={sentenct: sentence }
    }
}