1. 程式人生 > >react navigation 高階: 任意控制元件內獲取 navigation 屬性

react navigation 高階: 任意控制元件內獲取 navigation 屬性

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.