Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - React Navigation - How to calling function from another file and use it on headerRight onPress?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...