React Native React Navigation 标题按钮事件

13

你好,我正在尝试在我的导航器右按钮中绑定一个函数,但是出现了错误。

这是我的代码:

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>
        );
    }
}

出现以下错误:

undefined is not an object (evaluating 'this.alertMe.bind')

当我在render函数中使用该方法时,它运行得很好,但在NavigationOption中无法处理它。我应该怎么做来解决这个问题。

4个回答

52

你应该在你的导航函数中使用这个

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()} />
    };
};

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

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

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

_saveDetails() {
**write you logic here for **
}

如果您正在使用 "this",则无需绑定函数。


@ashutosh_pandey 只有一个问题。我可以在 _saveDetails() 函数中使用 this.state 吗? - Heril Muratovic
@HerilMuratovic,是的,你可以使用它。回复晚了,抱歉。 - ashutosh pandey
2
使用 this.setState 时,请像这样绑定:this.props.navigation.setParams({ handleSave: this._saveDetails.bind(this) }); - a_rahmanshah
我正在做同样的事情,但我的按钮没有出现在标题中...为什么会这样? - Ali Yar Khan

3
可能与上面相同...
   class LoginScreen extends React.Component {
      static navigationOptions = {
        header: ({ state }) => ({
          right: <Button title={"Save"} onPress={state.params.showAlert} />
        })
      };

      showAlert() {
        Alert.alert('No Internet',
          'Check internet connection',
          [
            { text: 'OK', onPress: () => console.log('OK Pressed') },
          ],
          { cancelable: false }
        )
      }

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

      render() {
        return (
          <View />
        );
      }
    }

3

react-navigation v5版本如下:

export const ClassDetail = ({ navigation }) => {
  const handleOnTouchMoreButton = () => {
    // ...
  };

  useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <TouchableOpacity onPress={handleOnTouchMoreButton}>
          <Icon name="more" />
        </TouchableOpacity>
      ),
    });
  }, [navigation]);

  return (
    // ...
  )
}

1
这是关于导航v4的内容。您需要在功能组件外修改导航选项。您的按钮事件需要通过导航传递参数。
pageName['navigationOptions'] = props => ({
    headerRight:  ()=>
         <TouchableOpacity onPress={() => props.navigation.navigate("pageRoute", 
{"openAddPopover": true})  } ><Text>+</Text></TouchableOpacity>    })

然后在你的函数组件中,你可以使用该参数来执行以下操作:

useLayoutEffect(() => {
   doSomethingWithYourNewParamter(navigation.getParam("openAddPopover"))
}, [navigation])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接