使用参数从React Navigation导航器内部调用组件函数

时间:2019-09-02 19:39:47

标签: javascript reactjs react-native react-navigation

使用React Nav v4,我试图在ComponentA.js中设置参数...

componentDidMount(){
    ...

    this.props.navigation.setParams({ 
        goToTop: this.goToTop.bind(this) 
    });

}

并从我的initNavigator.js中的createBottomTabNavigator> tabBarOnPress中调用它们

const MainTabs = createBottomTabNavigator({
HomeStack: {
    screen: HomeCard,
    navigationOptions: (navigation, navigationOptions) => ({

        ...,
        tabBarOnPress: ({navigation, defaultHandler}) => {
            const { isFocused, state, goBack, routes } = navigation;

            // NEED TO CALL HERE

        },

我已经尝试过navigation.getParam('goToTop','someDefult')

Logs someDefult

console.log(navigation.state)

{ 
isTransitioning: false,
index: 0,
key: 'HomeStack',
routeName: 'HomeStack',
params: undefined,
routes: 
[ { routeName: 'Home',
    key: 'id-1567452719174-1',
    params: { goToTop: [Function: bound ] } } ] }

还有没有理由解释为什么params没有定义,但是路由params包含函数吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

已解决,方法是调用state.routes [0] .params.goToTop();

const MainTabs = createBottomTabNavigator({
HomeStack: {
    ...
    ...
    navigationOptions: (navigation, navigationOptions) => ({

        ...,
        tabBarOnPress: ({navigation, defaultHandler}) => {
            const { isFocused, state, goBack, routes } = navigation;

            // NEED TO CALL HERE
            state.routes[0].params.goToTop();

        },