React Navigation - How to calling function from an

2019-08-20 16:52发布

I wonder there's a way to using headerRight onPress to doing something like calling Alert:

I have a function inside MyPet.js with the code :

_alert=()=>{
  alert('saving')
}

and in router.js I have a list of all screen I've used to navigating with a piece of code like :

export const MyPatientStack =  StackNavigator({
  MyPatient: {
    screen: MyPatient,
    navigationOptions: {
      tabBarLabel: 'My Patient',
      tabBarIcon: ({ tintColor, focused }) => <FontAwesome name="wheelchair" size={25} color={tintColor} />,
      headerTitle: 'My Patient',
      headerStyle: {
        backgroundColor: '#8B0000',
      },
      headerLeft: <HeaderBackButton tintColor="#FFF" onPress={() => navigation.goBack()} />,
// and here I want to call the function of _alert() from MyPet.js
      headerRight: <FontAwesome name='search' size={20} color="#FFF" onPress={_alert()}/>,      
      headerTintColor: '#fff',
      headerTitleStyle: {
        fontWeight: 'bold',
        textAlign:'center',
        flex:1
      },
    }
  }
})

Have tried it and the code doesn't find variable _alert

How can I do that?

any feedback are welcome

1条回答
Animai°情兽
2楼-- · 2019-08-20 17:27

Since your Navigation component has no reference to what is in your Pet.js component, you may try the following way

Use navigationOptions in your Pet.js component as

// Inside the class
// Since navigationOptions have no access to this parameter of the class, therefore you need to pass them as params
static navigationOptions = ({navigation}) => {
        const {params}} = navigation.state;
        return {
            headerRight: <FontAwesome name='search' size={20} color="#FFF" onPress={() => params.showAlert()}/> />

        };
    };


 componentDidMount() {
        this.props.navigation.setParams({
            showAlert: this.alertShower
        });
    }

alertShower = () =>  Alert.alert('Success', 'Hello')
查看更多
登录 后发表回答