Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

react native - Pass Props StackNavigator

i try to pass props on stacknavigator, here my code

const MainCart = StackNavigator({
  Cart: {
    screen: CartScreen
  },
  Checkout: {
    screen: COScreen
  }

  /* how to pass 'myprops' in this area? */

});


export default class ReactNative_RefreshControl extends Component {

  constructor(props) {
    super(props)
  }

  render() {
    console.log('ReactNative_RefreshControl this.props.myparam : ' + this.props.myparam);
    return <MainCart myprops = {
      this.props.myparam
    }
    />;

    //https://reactnavigation.org/docs/navigators/stack#Navigator-Props
  }


}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

React Navigation < 5

If you want to pass props in that place you have to use it like this.

const MainCart = StackNavigator({
 Cart: {
    screen: props=> <CartScreen {...props} screenProps={other required prop}>
 },
 Checkout: {
    screen: COScreen
 }

If you want to pass props when navigating the solution by Sagar Chavada is useful

React Navigation - 5

You have to either use React Context(recommended) or a render callback to solve this. Documentation link

Below example shows how to do with React Context

In your parent of the navigator file create a context

<AppContext.Provider value={other required prop}>
   <YourNavigator/>
</AppContext.Provider>

In your navigator file

const YourNavigator = () => (
  <AppStack.Navigator>
     <AppScreen.Screen name={"routeName"} component={AppContextWrapper}/>
  </AppStack.Navigator>

const AppContextWrapper = ({ navigation, route }) => (
  <AppContext.Consumer>
    {(other required prop) => (
       <YourScreenComponent {...other required prop}/>
    )}
  </AppContext.Consumer>
);

another easy (not recommended) - Callback method

<Stack.Screen name="Home">
  {props => <HomeScreen {...props} extraData={someData} />}
</Stack.Screen>

Note: By default, React Navigation applies optimizations to screen components to prevent unnecessary renders. Using a render callback removes those optimizations. So if you use a render callback, you'll need to ensure that you use React.memo or React.PureComponent for your screen components to avoid performance issues.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...