react.js ReactComponent不提供setState()?

gho*_*t23 8 javascript reactjs

我似乎误解了React.js的一些基本部分.

http://facebook.github.io/react/docs/component-api.html

它说,一个react组件有像setState()这样的方法.

但是当我这样做时:

var MyComp = React.createClass({

   getInitialState: function() {
      return {dummy: "hello"};
   },

   render: function() { return React.DOM.h1(null, this.state.dummy + ", world!") }
}

var newComp = MyComp(null);

React.renderComponent(newComp, myDomElement);
MyComp.setState({dummy: "Good Bye"}); // Doesn't work. setState does not exist
newComp.setState({dummy: "Good Bye"}); // Doesn't work either. setState does not exist
Run Code Online (Sandbox Code Playgroud)

没有找到setState()方法.但是在文档中它说组件API,那么我在这里遇到了什么问题?

Fel*_*ing 12

根据这篇博文本文,调用MyComp不再返回实例,它返回一个轻量级描述符.

反模式:

var MyComponent = React.createClass({
  customMethod: function() {
   return this.props.foo === 'bar';
  },
  render: function() {
  }
});

var component = <MyComponent foo="bar" />;
component.customMethod(); // invalid use!
Run Code Online (Sandbox Code Playgroud)

正确用法:

var MyComponent = React.createClass({
  customMethod: function() {
   return this.props.foo === 'bar';
  },
  render: function() {
  }
});

var realInstance = React.renderComponent(<MyComponent foo="bar" />, root);
realInstance.customMethod(); // this is valid
Run Code Online (Sandbox Code Playgroud)