简体   繁体   中英

How to use props and navigation together in one functional component in react native

I want to use props and {navigation} in one functional component in react-navigation version 5

This is my code:

const Header =(props, {navigation})=>{

return()}

But it doesn't work, I can't activate drawer. It returns following error :

undefined is not an object(evaluating 'navigation.openDrawer)

You need to lookup destructuring: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Example:

const Header = (props)=> {
  const { navigation } = props;

  // Now you can use `navigation`
  // Instead of destructuring, you can also use `props.navigation`
}

If your component is not registered as a route in routes object, you either have to pass the navigation prop manually, or you can do this. Because only the components that are registered as routes will have access to the navigation object.

Wrap it with withNavigation from react-navigation , like this:

import { withNavigation} from 'react-navigation'; 

const YourFunctionalComponent = props => { 
   // your component logic
};

// the navigation now will be in props
export default withNavigation(YourFunctionalComponent)

This works with any custom component deep in the tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM