如何在 React Native 的一个功能组件中同时使用道具和导航
How to use props and navigation together in one functional component in react native
我想在 react-navigation
版本 5
的一个功能组件中使用 props
和 {navigation}
这是我的代码:
const Header =(props, {navigation})=>{
return()}
但是它不起作用,我无法激活抽屉。它 returns 以下错误:
undefined is not an object(evaluating 'navigation.openDrawer)
您需要查找解构:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
示例:
const Header = (props)=> {
const { navigation } = props;
// Now you can use `navigation`
// Instead of destructuring, you can also use `props.navigation`
}
如果您的组件未在路由对象中注册为路由,您要么必须手动传递导航道具,要么可以这样做。因为只有注册为路由的组件才能访问导航对象。
用react-navigation中的withNavigation包裹它,像这样:
import { withNavigation} from 'react-navigation';
const YourFunctionalComponent = props => {
// your component logic
};
// the navigation now will be in props
export default withNavigation(YourFunctionalComponent)
这适用于树深处的任何自定义组件。
我想在 react-navigation
版本 5
props
和 {navigation}
这是我的代码:
const Header =(props, {navigation})=>{
return()}
但是它不起作用,我无法激活抽屉。它 returns 以下错误:
undefined is not an object(evaluating 'navigation.openDrawer)
您需要查找解构:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
示例:
const Header = (props)=> {
const { navigation } = props;
// Now you can use `navigation`
// Instead of destructuring, you can also use `props.navigation`
}
如果您的组件未在路由对象中注册为路由,您要么必须手动传递导航道具,要么可以这样做。因为只有注册为路由的组件才能访问导航对象。
用react-navigation中的withNavigation包裹它,像这样:
import { withNavigation} from 'react-navigation';
const YourFunctionalComponent = props => {
// your component logic
};
// the navigation now will be in props
export default withNavigation(YourFunctionalComponent)
这适用于树深处的任何自定义组件。