这里的类似问题似乎是范围问题的结果,对我而言并非如此。我试图创建函数处理程序来设置App
组件的状态。这些绑定到App
并存储以便重新使用。
createLinkHandler(link)
{
let pageState = this._pages[link];
this.linkHandlers[link] = (function(newState) {
this.setState({'page': newState});
}).bind(this._app, pageState);
}
在函数内记录this
可验证函数是否已正确绑定到App
组件。所以我做了一个简单的测试来验证setState()
是否在正常条件下工作(main.js):
var myApp = <App/>
myApp.setState({'page': 1});
在上述两种情况下,我都留下了Uncaught TypeError: {this/myApp}.setState is not a function
this
/ myApp
的记录输出:https://s26.postimg.org/ejfxd1djd/Capture.png
更新(这是我的App
课程):
export class App extends React.Component
{
constructor(props)
{
super(props);
this.state = {
'page': this._pages.LOGIN,
'style': this._styles.DEFAULT
};
}
// etc.
}
答案 0 :(得分:2)
最好输入创建反应组件的属性,如下所示:
class myApp extends React.Component {
constructor() {
super(this.props);
this.state = {
'page': this._pages.LOGIN,
'style': this._styles.DEFAULT,
...this.props // overrides defaults if existing
}
this.createLinkHandler = this.createLinkHandler.bind(this)
}
createLinkHandler(link)
{
// no underscore dongle
let pageState = this.pages[link];
// set new state only inside.
// do whatever you want to do over here.
this.setState({...state, xyz: 'test'})
}
render () {
return (
<NavBar { ...this.pages, this.createLinkHandler } />
)
}
}
class NavBar extends React.Component {
constructor(){
super(this.props)
this.state = { ...this.props }
}
render() {
// call on click the function this will then be executed in the app
// context and there you can change the App state.
<div>
<a OnClick={this.props.createLinkHandler('linkxyz')} />
<a OnClick={this.props.createLinkHandler('linkxyz')} />
<a OnClick={this.props.createLinkHandler('linkxyz')} />
</div>
}
}
// creating the react class with
// certain properties
const props = {page: 1}
var myApp = <App {...props} />
&#13;
现在你有{page:1}
的开始状态,你可以通过创建链接处理程序来扩展它!希望我能帮到你一点。
答案 1 :(得分:0)
如果您不喜欢在构造函数中进行手动绑定,则可以使用箭头功能。箭头功能会自动进行绑定,并且不会出现与范围相关的问题
createLinkHandler = (link) =>
{
// no underscore dongle
let pageState = this.pages[link];
// set new state only inside.
// do whatever you want to do over here.
this.setState({...state, xyz: 'test'})
}