我在构造函数中声明了状态并尝试从renderScene
调用它,但this.state
总是null
出错了什么?
我的代码是;
var _=require('underscore');
class ReactNotes extends React.Component {
constructor (props) {
super(props);
this.state = {
selectedNote: {title:"", body:""},
notes: {
1: {title: "Note 1", body: "body", id: 1},
2: {title: "Note 2", body: "body", id: 2}
}
};
} render () {
return (
<Navigator initialRoute={{name: 'home'}}
renderScene={this.renderScene}
navigationBar=
{
<Navigator.NavigationBar
routeMapper={NavigationBarRouteMapper}
style={styles.navBar}
/>
}
/> );
}
renderScene (route, navigator) {
switch (route.name) {
case 'home':
return (
<HomeScreen navigator={navigator} notes= {_(this.state.notes).toArray()} onSelectNote={(note) => navigator.push({name:"createNote", note: note})}/>
);
case 'createNote':
return (
<NoteScreen note={this.state.selectedNote}
onChangeNote={(note) => this.updateNote(note)}/>
);
} }
}
输出如下:
答案 0 :(得分:0)
您可以使用箭头功能
绑定您的功能renderScene = (route, navigator) => {
//...
}
//then call your function in your navigator as
renderScene={this.renderScene}
或
// You can use bind() to preserve `this`
renderScene={this.renderScene.bind(this)}>
// Or you can use arrow function this way
renderScene={() => this.renderScene()}>