React Native:按钮onPress无法正常工作

问题描述 投票:2回答:1

导航无法按下按钮。这是我的登录页面。我想从主屏幕注销登录屏幕onPressLogout()

index.js

class Profile extends Component{
static propTypes = {
    navigator: PropTypes.shape({
        getCurrentRoutes: PropTypes.func,
        jumpTo: PropTypes.func,
    }),
}
onPressLogout() {
    const routeStack = this.props.navigator.getCurrentRoutes();
    this.props.navigator.jumpTo(routeStack[0]);
}
render(){
  return (
         <Container>
             <View style={styles.container}>        
               <Header>
                     <Button 
                     style={styles.button}
                     onPress={() => this.onPressLogout()}
                     >
                     <Icon name="ios-power" />
                     </Button>
                     <Title>Logout</Title>
               </Header>
            </Container>
 );
}

并在routeStack中

const routeStack = [
{ name: 'Login', component: Login},  
]
javascript react-native navigation
1个回答
0
投票

要么使用.bind()来改变this的背景。或者,使用箭头功能。

bind()

这需要一个构造函数。

constructor() {
  super();
  this.onPressLogout = this.onPressLogout.bind(this);
}

箭头功能

onPressLogout = () => {
  const routeStack = this.props.navigator.getCurrentRoutes();
  this.props.navigator.jumpTo(routeStack[0]);
}

边注:

你可以在这里做一些ES6解构

onPressLogout = () => {
  const {
     navigator: {
       getCurrentRoutes,
       jumpTo
     }
  } = this.props;
  const routeStack = getCurrentRoutes();
  jumpTo(routeStack[0]);
}
© www.soinside.com 2019 - 2024. All rights reserved.