react navigation 高阶: 任意控件内获取 navigation 属性

本文详细介绍了如何在React Native应用中使用React Navigation库来传递navigation prop。通过withNavigation高阶组件,即使在深层嵌套的子组件中也能轻松访问navigation功能,如goBack等。文章提供了具体代码示例,展示了如何避免undefined is not a function异常,并确保Back按钮正确工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://reactnavigation.org/docs/en/connecting-navigation-prop.html

 

Access the navigation prop from any component

withNavigation is a higher order component which passes the navigation prop into a wrapped Component. It's useful when you cannot pass the navigation prop into the component directly, or don't want to pass it in case of a deeply nested child.

import React from 'react';
import { Button } from 'react-native';
import { withNavigation } from 'react-navigation';

export default class MyBackButton extends React.Component {
  render() {
    // This will throw an 'undefined is not a function' exception because the navigation
    // prop is undefined.
    return <Button title="Back" onPress={() => { this.props.navigation.goBack() }} />;
  }
}

To resolve this exception, you could pass the navigation prop in to MyBackButton when you render it from a screen, like so: <MyBackButton navigation={this.props.navigation} />.

Alternatively, you can use the withNavigation function to provide the navigation prop automatically (through React context, if you're curious). This function behaves similarly to Redux's connect function, except rather than providing the dispatch prop to the component it wraps, it provides the navigationprop.

import React from 'react';
import { Button } from 'react-native';
import { withNavigation } from 'react-navigation';

class MyBackButton extends React.Component {
  render() {
    return <Button title="Back" onPress={() => { this.props.navigation.goBack() }} />;
  }
}

// withNavigation returns a component that wraps MyBackButton and passes in the
// navigation prop
export default withNavigation(MyBackButton);

Using this approach, you can render MyBackButton anywhere in your app without passing in a navigationprop explicitly and it will work as expected.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值