在React-Native中使用嵌套的StackNavigator和TabNavigator传递道具

时间:2018-06-22 09:50:33

标签: reactjs react-native react-navigation react-native-navigation

export default class Home extends React.Component {
      static navigationOptions = {  headerLeft: null, header: null};
      constructor(props){
         super(props);
         this.state = {
           userID: this.props.navigation.getParam('userId')
         };
       }
      render() {
        userId = this.props.navigation.getParam('userId');
        return <HomeNav userId={this.state.userId}/>;
      }
    }


    const HomeNav = TabNavigator({
    MyEvents: { screen: props => <MyEvents userId={userId}/>},
      MyTickets: { screen: props => <MyTickets userId={userId}/>},
    }, {tabBarPosition:'bottom'});

我的屏幕结构是:

  • Stacknavigator(登录和主页)
  • 主页是选项卡导航器(事件和票证)

我知道如何将userId从登录名传递到家庭(您可以在上方看到我的信息)。我尝试了多种方法将userID传递给选项卡导航器,然后传递给其子级。我上面尝试的方式有效,但是我想知道如何正确执行此操作,并能够访问MyTickets和MyEvents中的导航道具。谢谢。

1 个答案:

答案 0 :(得分:4)

export default class Home extends React.Component {
    static navigationOptions = {
        headerLeft: null,
        header: null
    };
    constructor(props) {
        super(props);
        this.state = {
            userID: this.props.navigation.getParam('userId')
        };
    }
    render() {
        userId = this.props.navigation.getParam('userId');
        return <Home userId = {
            this.state.userId
        }
        />;
    }
}

const Home = (props) => {
    const user = {
        id: props.userId
    }
    return ( <
        HomeNav screenProps = {
            user
        }
        />
    );
}


const HomeNav = TabNavigator({
    MyEvents: MyEvents,
    MyTickets: MyTickets,
}, {
    tabBarPosition: 'bottom'
});

现在,在MyEvents和MyTickets标签中,您可以将值访问为

const { screenProps } = this.props;
const userId =screenProps.id;

希望有帮助!