【问题标题】:React Native :Button onPress not workingReact Native:按钮 onPress 不起作用
【发布时间】:2017-08-07 11:07:18
【问题描述】:

按下按钮时导航不起作用。这是我的登录页面。我想退出 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>
 );
}

在路由栈中

const routeStack = [
{ name: 'Login', component: Login},  
]

【问题讨论】:

    标签: javascript react-native navigation


    【解决方案1】:

    使用.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]);
    }
    

    【讨论】:

    • 两种方法都试过了,还是一样的错误undefined is not an object:evaluating _this$props$navigator.getCurrentRoutes
    • 您是否可以只使用 console.log this.props.navigator 并回复结果?
    • 控制台显示一些错误。我试图提醒但没有结果。
    猜你喜欢
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多