React Native Navigation 6.0:向自定义Header传递函数Props更新父组件状态
核心思路
要实现点击自定义Header按钮更新父屏幕状态,关键是将父屏幕的状态更新函数通过导航的options传递给自定义Header组件,然后在Header的按钮点击事件中调用该函数。由于RN Navigation 6.0中屏幕的options支持动态设置,我们可以在父屏幕内部通过navigation.setOptions()把函数传入Header。
代码示例
1. 自定义Header组件
先创建独立的自定义Header组件,接收父屏幕传递的更新函数作为props:
import React from 'react'; import { View, TouchableOpacity, Text } from 'react-native'; import { HeaderBackButton } from '@react-navigation/elements'; const CustomHeader = ({ navigation, onUpdateCount }) => { return ( <View style={{ flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, height: 56, backgroundColor: '#fff' }}> {/* 返回按钮(可选) */} <HeaderBackButton onPress={() => navigation.goBack()} /> <Text style={{ fontSize: 18, fontWeight: 'bold', flex: 1, textAlign: 'center' }}>自定义Header</Text> {/* 触发状态更新的按钮 */} <TouchableOpacity onPress={() => onUpdateCount()}> <Text style={{ fontSize: 16, color: '#007AFF' }}>点击加1</Text> </TouchableOpacity> </View> ); }; export default CustomHeader;
2. 父屏幕组件
在父屏幕中定义状态和更新函数,通过navigation.setOptions()将函数传递给自定义Header:
import React, { useState, useCallback, useEffect } from 'react'; import { View, Text, StyleSheet } from 'react-native'; import CustomHeader from './CustomHeader'; const HomeScreen = ({ navigation }) => { const [count, setCount] = useState(0); // 用useCallback缓存函数,避免不必要的重渲染 const updateCount = useCallback(() => { setCount(prev => prev + 1); }, []); useEffect(() => { // 动态设置导航选项,将更新函数传递给自定义Header navigation.setOptions({ header: () => <CustomHeader navigation={navigation} onUpdateCount={updateCount} />, }); }, [navigation, updateCount]); return ( <View style={styles.container}> <Text style={styles.countText}>当前计数:{count}</Text> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, countText: { fontSize: 20, }, }); export default HomeScreen;
3. 导航栈配置
在导航栈中注册父屏幕即可:
import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import HomeScreen from './HomeScreen'; const Stack = createStackNavigator(); const App = () => { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} /> </Stack.Navigator> </NavigationContainer> ); }; export default App;
关键注意事项
- 使用
useCallback缓存状态更新函数:避免每次父组件重渲染时生成新的函数实例,导致Header不必要的重渲染。 - 动态设置
header选项:必须在组件内部通过navigation.setOptions()传递函数,不能在Stack.Screen的options静态配置中直接引用组件内部的函数(静态配置无法访问组件的状态和函数)。 - 类型检查(可选):如果使用TypeScript,可以为自定义Header的props添加类型定义,避免类型错误。
内容的提问来源于stack exchange,提问作者SOHAIL MADAN
相关产品推荐
相关产品推荐

