如何在ReactJS中使用setState?

时间:2015-12-19 06:54:16

标签: reactjs

在以下代码中,我认为文本应在3秒后更新为新文本:

https://jsfiddle.net/smrfcr9x/1/

var Component = React.createClass({

  render: function() {
    return React.DOM.span(null, "hello " + this.props.text);
  }

});

var aComponent = React.render(

  React.createElement(Component, {
    text: "abcd"
  }),

  document.getElementById("app")

);

setTimeout(function() {
  console.log("now setting state");
  aComponent.setState({
    text: "lmno"
  });
}, 3000);

它是如何实际完成的?

1 个答案:

答案 0 :(得分:0)

好的,我想我明白了。需要设置状态的代码,并在render中使用this.state代替this.props

https://jsfiddle.net/smrfcr9x/7/

var Component = React.createClass({

  getInitialState: function() {
    return {
      text: this.props.text,
    };
  },

  render: function() {
    return React.DOM.span(null, "hello " + this.state.text);
  }

});