gpt4 book ai didi

javascript - react.js ReactComponent 不提供 setState()?

转载 作者:数据小太阳 更新时间:2023-10-29 04:08:01 24 4
gpt4 key购买 nike

我似乎误解了 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 postthis 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com