我正在尝试隐藏/显示React Native Toolbar标题中的按钮。我想在用户登录后显示按钮。我得到错误undefined不是this.state.status上的对象。如何在工具栏中显示状态?
export default class TestSC extends React.Component {
constructor(){
super();
this.state ={
status:false
}
}
static navigationOptions = ({navigation})=> {
return {
title: 'Tin Tin Foil',
headerRight: (
<View style={styles.twoButtonView}>
{(this.state.status == true) ?
<TouchableOpacity onPress={this._refreshButtonPress}>
<Image source={require('../img/ic_search_white.png')} style={styles.refrgeshButton} />
</TouchableOpacity>
: null}
<Button
onPress={() => navigation.navigate('Login')}
title="Login" color="#fff" />
</View>
),
}};
toggleStatus(){
this.setState({
status:!this.state.status
});
console.log('toggleStatus: '+ this.state.status);
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Test</Text>
<TouchableHighlight onPress={()=>this.toggleStatus()}>
<Text> Click Me Toggle </Text>
</TouchableHighlight>
</View>
);
}
}
答案 0 :(得分:1)
您可以使用navigation params
来实现此目标。
在设置组件状态时,您还需要设置Navigator参数。
this.props.navigation.setParams({
status: true
})
在标题中使用导航器参数。
navigation.state.params.status == true
完整示例
export default class TestSC extends React.Component {
constructor() {
super();
this.state = {
status: false
}
}
static navigationOptions = ({navigation, screenProps}) => {
if (!navigation.state.params) {
navigation.state.params = {}
}
return {
title: 'Tin Tin Foil',
headerRight: (
<View style={styles.twoButtonView}>
{(navigation.state.params.status == true) ?
<TouchableOpacity onPress={this._refreshButtonPress}>
<Text>Login</Text>
</TouchableOpacity>
: null}
</View>
),
}
};
toggleStatus() {
this.setState(pre => {
pre.status = !pre.status
this.props.navigation.setParams({
status: pre.status
})
return pre
})
console.log('toggleStatus: ' + this.state.status);
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Test</Text>
<TouchableHighlight onPress={()=>this.toggleStatus()}>
<Text> Click Me Toggle </Text>
</TouchableHighlight>
</View>
);
}
}