React Native React导航标题按钮事件

And*_*mel 12 react-native

您好我正在尝试在导航器右键中绑定一个函数,

但它给出了错误.

这是我的代码:

import React, { Component } from 'react';
import Icon from 'react-native-vector-icons/FontAwesome';
import Modal from 'react-native-modalbox';
import { StackNavigator } from 'react-navigation';
import {
   Text,
   View,
   Alert,
   StyleSheet,
   TextInput,
   Button,
   TouchableHighlight
} from 'react-native';

import NewsTab from './tabs/news-tab';
import CustomTabBar from './tabs/custom-tab-bar';

export default class MainPage extends Component {
    constructor(props) {
        super(props);  
    }

    alertMe(){
        Alert.alert("sss");
    }

    static navigationOptions = {
        title: 'Anasayfa',
        headerRight: 
            (<TouchableHighlight onPress={this.alertMe.bind(this)} >
                <Text>asd</Text>
             </TouchableHighlight>)        
    };

    render() {
        return(
            <View>

            </View>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

并得到这样的错误:

undefined不是对象(评估'this.alertMe.bind')

当我在渲染函数中使用此方法时,它工作得很好但在NavigatonOption中我无法处理它.我能为这个问题做些什么.

ash*_*dey 45

您应该在导航器功能中使用它

static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state;
    return {
        title: '[ Admin ]',
        headerTitleStyle :{color:'#fff'},
        headerStyle: {backgroundColor:'#3c3c3c'},
        headerRight: <Icon style={{ marginLeft:15,color:'#fff' }} name={'bars'} size={25} onPress={() => params.handleSave()} />
    };
};
Run Code Online (Sandbox Code Playgroud)

使用componentwillmount,以便它可以表示您调用函数的位置.

componentDidMount() {
this.props.navigation.setParams({ handleSave: this._saveDetails });
}
Run Code Online (Sandbox Code Playgroud)

然后你可以在函数中编写你的逻辑

_saveDetails() {
**write you logic here for **
}
Run Code Online (Sandbox Code Playgroud)

**如果您使用此**,则无需绑定功能**

  • 你是一个救生员.它将完全奏效. (2认同)
  • 要使用this.setState,请这样绑定:`this.props.navigation.setParams({handleSave:this._saveDetails.bind(this)});` (2认同)