React Navigation - 如何从另一个文件调用函数并在headerRight onPress上使用它?

时间:2018-04-05 10:49:27

标签: javascript react-native react-navigation

我想知道有一种方法可以使用headerRight onPress来执行调用Alert之类的操作:

我在MyPet.js内有一个函数,代码为:

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

并且在router.js我有一个列表,列出了我曾经用一段代码导航的所有屏幕:

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
      },
    }
  }
})

尝试过,代码找不到变量_alert

我该怎么做?

欢迎任何反馈

1 个答案:

答案 0 :(得分:2)

由于您的导航组件 没有参考Pet.js组件中的内容,您可以尝试以下方式

使用navigationOptions组件中的Pet.js作为

// 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')