无法在React Native NavigationOptions标头中设置事件处理程序

时间:2018-07-18 10:31:13

标签: react-native event-handling react-navigation

我是新来的本地人。我正在尝试设置事件处理程序以进行响应导航。我使用navigationOptioins-> headerRight->图标,并尝试设置_BananaButton来处理onPress事件。但这是行不通的。单击图标不会执行任何操作。 相同的事件处理程序在TouchableHighlight按钮中起作用,但在标题中却没有起作用。

请提出建议。

import React, { Component } from 'react';
import { Alert, Platform, StyleSheet, Button, Text, TouchableHighlight, TouchableOpacity, TouchableNativeFeedback, TouchableWithoutFeedback, View, Linking } from 'react-native';
import FruitViewer from './FruitViewer';
import Icon from 'react-native-vector-icons/FontAwesome';
import PropTypes from 'prop-types'; import {
  createStackNavigator,
} from 'react-navigation';

export class Touchables extends Component {
  _BananaButton() {
    const { navigate } = this.props.navigation;
    navigate('FruitViewer');
  }

  static navigationOptions = ({navigation}) => {
    console.log(this.props)
    //onPress={navigation.state.params.RightHandler}
    return {
      title: 'Home',
      headerStyle: { backgroundColor: 'white' },
      headerTitleStyle: { color: 'blue' },
      headerRight: (
        <Icon
              onPress={this._BananaButton}
              name='home'
              size={25} //onPress={() => alert('This is a button!')}
              color="#0000ff" //onPress={() => alert('This is a button!')}
              style={{height:25,width:25}}
              />
            ),
          }
  }

  constructor(props) {
    super(props);
    this._BananaButton = this._BananaButton.bind(this)
    console.log('constructor')
  }  

  render() {
    const { navigate } = this.props.navigation;

    return (
      <View style={styles.container}>    
        <TouchableHighlight onPress={this._BananaButton} underlayColor="white" >
          <View style={styles.button}>
            <Text style={styles.buttonText}>Banana</Text>
            </View>        
        </TouchableHighlight>   
      </View>
    );
  }
}

const styles = StyleSheet.create({..})

const App = createStackNavigator({
  Touchables: { screen: Touchables },
  FruitViewer: { screen: FruitViewer },

});

export default App;

1 个答案:

答案 0 :(得分:2)

您需要添加

componentDidMount() {
  this.props.navigation.setParams({ _BananaButton: this._BananaButton });
}

并像这样使用它:

<Icon
   onPress={navigation.getParam('_BananaButton')}

请阅读有关该主题Header buttons heandlers的反应导航文档