【问题标题】:React Navigation - How to calling function from another file and use it on headerRight onPress?React Navigation - 如何从另一个文件调用函数并在 headerRight onPress 上使用它?
【发布时间】:2018-04-05 10:49:26
【问题描述】:

我想知道有没有一种方法可以使用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

我该怎么做?

欢迎任何反馈

【问题讨论】:

    标签: javascript react-native react-navigation


    【解决方案1】:

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

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

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

    【讨论】:

    • 这意味着我需要删除router.js中的navigationOptions
    • 是的,这个config 是特定于你的Pet.js component,你可以在这里添加rest of the configuration
    • 这是heirarchynavigationOptionsRouteConfigs &gt; Screen Property &gt; StaticNagivatorConfig
    猜你喜欢
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 2021-03-17
    • 2022-08-18
    • 2016-03-11
    相关资源
    最近更新 更多