Javascript react.js ReactComponent不提供setState()?
我似乎误解了React.js的一些基本部分 在 它表示react组件有setState()之类的方法 但当我这么做的时候:Javascript react.js ReactComponent不提供setState()?,javascript,reactjs,Javascript,Reactjs,我似乎误解了React.js的一些基本部分 在 它表示react组件有setState()之类的方法 但当我这么做的时候: var MyComp = React.createClass({ getInitialState: function() { return {dummy: "hello"}; }, render: function() { return React.DOM.h1(null, this.state.dummy + ", world!") }
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,那么我这里错了什么呢?根据这一点,调用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(){
返回this.props.foo=='bar';
},
render:function(){
}
});
var分量=;
component.customMethod();//无效使用!
正确用法:
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
var MyComponent=React.createClass({
customMethod:function(){
返回this.props.foo=='bar';
},
render:function(){
}
});
var realInstance=React.renderComponent(,根);
realInstance.customMethod();//这是有效的
看一看newComp
实际上不是组件的一个实例,它是一个描述符(MyComp.setState
当然不能工作,因为MyComp
基本上就是“类”)。啊哈。所以,这些文件是错误的。不是React.createClass创建组件实例,而是React.renderComponent创建。这是有道理的。文档暗示调用MyComp(null)
应该返回一个实例,它在AFAIK的某个时候就这样做了。我会检查是否/如何更新。啊,是的,你说得对。您想回答这个问题吗,这样我就可以标记它了?从组件外部调用组件内的函数确实不是一个好主意,除非您将回调传递给某个父子关系。