Javascript React本机引用未定义
我目前正在开发一个应用程序,以下是与我的bug相关的基本代码: 以下是渲染函数:Javascript React本机引用未定义,javascript,react-native,Javascript,React Native,我目前正在开发一个应用程序,以下是与我的bug相关的基本代码: 以下是渲染函数: render() { return ( <ScrollableTabView> <NavigatorIOS translucent={false} initialRoute={{ component: MenuList, title: '', passProps: { hideNavBar: this.hideN
render() {
return (
<ScrollableTabView>
<NavigatorIOS
translucent={false}
initialRoute={{
component: MenuList,
title: '',
passProps: { hideNavBar: this.hideNavBar,
showNavBar: this.showNavBar,
toggleFav: this.toggleFav,
getFavImg: this.getFavImg,
},
}}
navigationBarHidden={this.state.hideNavBar}
style={{ flex: 1 }}
barTintColor="#1f3157"
titleTextColor="#f6f6f6"
tabLabel="Menu"
/>
<NavigatorIOS
ref="nav"
translucent={false}
initialRoute={{
component: FavoritesList,
title: '',
passProps: { hideNavBar: this.hideNavBar,
showNavBar: this.showNavBar,
favs: this.state.favs,
},
}}
navigationBarHidden={this.state.hideNavBar}
style={{ flex: 1 }}
barTintColor="#1f3157"
titleTextColor="#f6f6f6"
tabLabel="Favorites"
/>
<SpecialsList tabLabel="Specials" />
</ScrollableTabView>
);
我现在遇到的错误是,favChange
函数中未定义this.refs.nav
。我知道这肯定是这个
的问题,但我一点儿也不知道如何解决它
提前谢谢 这可能是因为“这个”绑定。
this.favChange=this.favChange.bind(this)
可以尝试在构造函数或初始化代码中添加此代码吗 这可能是因为“这个”绑定。
this.favChange=this.favChange.bind(this)
可以尝试在构造函数或初始化代码中添加此代码吗 还没有深入了解细节,您是否尝试过
toggleFav:this.toggleFav.bind(this)
而不是toggleFav:this.toggleFav
,因为您说过this一定有问题?(React Native是否有不同的直接修改状态的规则?例如,this.state.favs[item.title]=item
在常规的React land中是不允许的;任何直接修改状态的东西,而toggleFav
都可以,这是不允许的。)@DaveNewton在几乎所有情况下都不应该这样做(毕竟是React),但有时只要通过setState(this.state)触发更新,就可以了
或其他等效方法。尝试将ref作为属性传递,secNav={this.refs.nav}
到第一个导航器,然后您应该能够执行this.props.secNav…
还没有查看详细信息,您是否尝试过切换fav:this.toggleFav.bind(this)
而不仅仅是toggleFav:this.toggleFav
,因为您说过this
一定有问题(React Native是否有不同的直接修改状态的规则?例如,this.state.favs[item.title]=item
在常规的React land中是不允许的;任何直接修改状态的东西,而toggleFav
都可以,这是不允许的。)@DaveNewton在几乎所有情况下都不应该这样做(毕竟是React),但有时只要通过setState(this.state)触发更新,就可以了
或其他等效方法。尝试将ref作为属性传递给第一个导航器,secNav={this.refs.nav}
,然后您应该能够执行this.props.secNav…
favChange
是一个箭头函数,应该自动绑定。在任何情况下,让海报试一试都最好用评论来表达。favChange
是一个箭头函数,应该自动绑定。在任何情况下,让海报尝试某样东西最好用评论来表达。
toggleFav = ( item ) => {
//if not a favorite / not in map
if ( !this.state.favs[item.title] ){
this.state.favs[item.title] = item;
this.state.favs[item.title].faved = true;
}
else if ( this.state.favs[item.title].faved ){
this.state.favs[item.title].faved = false;
}
else {
this.state.favs[item.title].faved = true;
}
this.favChange();
}
favChange = () => {
this.refs.nav.replace({
component: FavoritesList,
title: '',
passProps: {
hideNavBar: this.hideNavBar,
showNavBar: this.showNavBar,
favs: this.state.favs,
},
});
}