我想知道有一种方法可以使用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
我该怎么做?
欢迎任何反馈
答案 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')