【问题标题】:React Native React Navigation Header Button EventReact Native React 导航标题按钮事件
【发布时间】:2025-12-08 21:50:01
【问题描述】:

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

但它给出了错误。

这是我的代码:

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 不是对象(评估 'this.alertMe.bind')

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

【问题讨论】:

    标签: react-native react-navigation react-navigation-stack


    【解决方案1】:

    你应该在你的导航功能中使用它

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

    使用组件将挂载,以便它可以表示您正在调用函数的位置。

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

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

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

    **使用 this 不需要绑定函数**

    【讨论】:

    • @ashutosh_pandey 只有一个问题。我可以在 _saveDetails() 函数中使用 this.state 吗?
    • @HerilMuratovic 是的,你可以使用它。抱歉回复晚了。
    • 要使用 this.setState,像这样绑定:this.props.navigation.setParams({ handleSave: this._saveDetails.bind(this) });
    • 我也在做同样的事情,但我的按钮没有显示在标题中.. 为什么会这样?
    【解决方案2】:

    可能同上...

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

      【讨论】:

        【解决方案4】:

        这是用于导航 v4。您需要在功能组件之外修改导航选项。您的按钮事件需要通过导航传递参数。

        pageName['navigationOptions'] = props => ({
            headerRight:  ()=>
                 <TouchableOpacity onPress={() => props.navigation.navigate("pageRoute", 
        {"openAddPopover": true})  } ><Text>+</Text></TouchableOpacity>    })
        

        然后在您的功能组件中,您可以使用该参数执行以下操作:

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

        【讨论】: