在App.js中,如果我在 tabBarComponent 中分配了 this.state.cartAmount ...,则会显示错误
TypeError: TypeError: undefined is not an object (evaluating'_this.state.cartAmount')
,如果我将 tabBarComponent 设置为
{(this.state != null) ? this.state.cartAmount : '0.0'}
并点击 tabBarComponent 中的 TouchableOpacity 主页,即使我编写了箭头功能,它也会给出错误消息
HandleTabPressOne = () => {
this.setState({ cartAmount: '12.20' });
}
我认为构造函数中存在一些问题,请指导
const TabNavRoutes = createBottomTabNavigator({
Tab1: {screen: HomeScreenStack},
Tab2: {screen: Screen2},
Tab3: {screen: Screen3},
Tab4: {screen: Screen4}
},
{
tabBarComponent:({navigation}) => (
<View style={{flex: 0.1, backgroundColor: '#FF0000', borderColor: '#FF0000', borderWidth: 1}}>
<View style={{flexDirection:'row', justifyContent: 'space-around', alignItems: 'center', paddingTop: 5}}>
<TouchableOpacity onPress={() => this.HandleTabPressOne.bind() } style={{alignItems: 'center', marginLeft: 5}}>
<Text style={styles.textFAB}>Home</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate('Tab2')}style={{alignItems: 'center'}}>
<Text style={styles.textFAB}>History</Text>
</TouchableOpacity>
<View style={styles.cartFAB}>
<MaterialIcons name="shopping-basket" size={24} color="#FFFFFF" style={{marginTop: 10}} />
<Text style={styles.totalCart}>{ this.state.cartAmount} €</Text>
</View>
</View>
</View>
)});
const AppSwitchNavigator = createSwitchNavigator({
Welcome: { screen: splashScreen },
Dashboard: { screen: TabNavRoutes }
});
const AppContainer = createAppContainer(AppSwitchNavigator);
export default class App extends React.Component {
constructor(props){
super(props)
this.state = {
cartAmount: '18.50'
}
}
HandleTabPressOne() {
this.setState({ cartAmount: '12.20' });
alert(this.state.cartAmount)
}
render() {
return <AppContainer/>
}
}
答案 0 :(得分:1)
(this.state!= null && this.state!== undefined)吗? this.state.cartAmount:'0.0'}
答案 1 :(得分:0)
() => this.HandleTabPressOne.bind()
您在这里有2个绑定。您应该做箭头或绑定。尝试这样的事情:
<TouchableOpacity onPress={this.HandleTabPressOne}
您的方法可以绑定箭头
HandleTabPressOne = () => {
this.setState({ cartAmount: '12.20' });
alert(this.state.cartAmount)
}