要使用类组件覆盖导航选项,将类似于
export default class SomeClass extends Component {
static navigationOptions = ({ navigation }) => {
return {
title: navigation.getParam('headerTitle'),
}
}
componentDidMount() {
this.props.navigation.setParams({ headerTitle: someVariableThatComesFromExternalCall })
}
...
}
但是我该如何使用功能组件呢?
export default function SomeFunctionalCompoenent({ navigation }) {
// How and Where do I change the header title ?
useEffect(() => { navigation.setParams({ headerTitle: someVariableThatComesFromExternalCall })})
return (
...
)
}
答案 0 :(得分:2)
您仍然需要在功能组件上定义navigationOptions。您是这样做的:
export default function SomeFunctionalComponent({ navigation }) {
useEffect(() => {
navigation.setParams({
headerTitle: someVariableThatComesFromExternalCall
})
})
}
SomeFunctionalComponent.navigationOptions = ({ navigation }) => {
return {
title: navigation.getParam('headerTitle'),
}
}
答案 1 :(得分:2)
我怀疑接受的答案不是针对当前最新版本的react导航(5),而且绝对不适用于该版本,因此这是@ react-navigation / native的有效示例v5.7.2:
export default function SomeFunctionalComponent({ navigation }) {
useEffect(() => {
navigation.setOptions({
headerTitle: 'some other title',
})
}, [])
}
我已使用它来访问反应上下文-获取用户的名称和头像,以便为他们设置漂亮的标题栏。我在此粘贴了代码,以防它对任何人有帮助:
import React, { useContext, useEffect } from 'react';
import UserContext from '../context/UserContext';
const HomeScreen = ({ navigation }) => {
const userContext = useContext(UserContext);
useEffect(() => {
navigation.setOptions({
title : userContext.name,
headerLeft : () => (
<TouchableOpacity
onPress={() => {
navigation.openDrawer();
}}
>
<FastImage
style={styles.userPhoto}
resizeMode={FastImage.resizeMode.cover}
source={{ uri: userContext.avatar }}
/>
</TouchableOpacity>
),
});
}, [ userContext ]);
return (
// etc
);
}