我似乎误解了 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
找不到 setState() 方法。但是在文档中它说是 Component API,那么我在这里弄错了什么?
最佳答案
根据这个blog post和 this writeup ,调用 MyComp
不再返回实例,它返回一个轻量级描述符。
反模式:
var MyComponent = React.createClass({
customMethod: function() {
return this.props.foo === 'bar';
},
render: function() {
}
});
var component = <MyComponent foo="bar" />;
component.customMethod(); // invalid use!
正确用法:
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
关于javascript - react.js ReactComponent 不提供 setState()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25791955/