React Navigation - 如何从另一个文件调用函数并在 headerRight onPress 上使用它? [英] React Navigation - How to calling function from another file and use it on headerRight onPress?

查看:41
本文介绍了React Navigation - 如何从另一个文件调用函数并在 headerRight onPress 上使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道有没有一种方法可以使用 headerRight onPress 来执行诸如调用 Alert 之类的事情:

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

我在 MyPet.js 中有一个函数,代码如下:

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

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

router.js 中,我有一个所有屏幕的列表,其中列出了我曾经使用以下代码导航的所有屏幕:

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

试过了,代码没有找到变量_alert

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

我该怎么做?

欢迎任何反馈

推荐答案

因为您的导航组件没有引用Pet.js 组件,您可以尝试以下方式

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

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

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

这篇关于React Navigation - 如何从另一个文件调用函数并在 headerRight onPress 上使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆