将道具传递给createSwitchNavigator会破坏createAppContainer

时间:2019-02-25 05:55:02

标签: javascript reactjs react-native

以下代码在我的EXPO Native Native项目中运行良好:

const AppNavigator = createSwitchNavigator({
    Loading:Loading,
    Auth: AuthenticationNavigator,
    Main: MainNavigator
});

const AppContainer = createAppContainer(AppNavigator);

class App extends React.Component {
    render() {
        return <AppContainer/>
    }
}

我想将screenProps添加到我的createSwitchNavigator中。我使用了this example。这是我的代码:

const AppNavigator = createSwitchNavigator({
    Loading:Loading,
    Auth: AuthenticationNavigator,
    Main: MainNavigator
});
const AppNavigatorWithProps=(<AppNavigator screenProps={{testing:true}} />)

const AppContainer = createAppContainer(AppNavigatorWithProps);

class App extends React.Component {
    render() {
        return <AppContainer/>
    }
}

我收到以下错误:

TypeError: undefined is not an object (evaluating 'Component.router.getStateForAction')

This error is located at:
    in NavigationContainer (at App.js:42)
    in App (at withExpoRoot.js:22)
    in RootErrorBoundary (at withExpoRoot.js:21)
    in ExpoRootComponent (at renderApplication.js:34)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in AppContainer (at renderApplication.js:33)

我在做什么错了?

2 个答案:

答案 0 :(得分:1)

class App extends React.Component {
  render() {
    return <AppContainer screenProps={{ testing: true }} />
   }
 }

答案 1 :(得分:0)

您不需要用AppNavigator或其他任何东西包装createAppContainer

只需使用下面的周代答案即可:

class App extends React.Component {
    render() {
        return <AppNavigator screenProps={{
          //pass any object you need for ex
          testing:true
        }}/>
    }
}

但是我添加了如下有关使用道具的其他信息:

要访问这些道具,您只需使用:

console.log(this.props.screenProps.testing)

createSwtichNavigator中定义的任何屏幕上,

例如在您的代码中:

Loading, Auth, and Main应该得到道具

class Loading extends React.Component {
    componentWillMount(){
      console.log(this.props.screenProps.testing)
    }
    render() {
        return (<View/>)
    }
}
  

注意:   我已经使用React Navigation V2

测试了代码