Ven*_*sky 6 react-native react-navigation
要使用类组件覆盖导航选项,将类似于
export default class SomeClass extends Component {
static navigationOptions = ({ navigation }) => {
return {
title: navigation.getParam('headerTitle'),
}
}
componentDidMount() {
this.props.navigation.setParams({ headerTitle: someVariableThatComesFromExternalCall })
}
...
}
Run Code Online (Sandbox Code Playgroud)
但是我该如何使用功能组件呢?
export default function SomeFunctionalCompoenent({ navigation }) {
// How and Where do I change the header title ?
useEffect(() => { navigation.setParams({ headerTitle: someVariableThatComesFromExternalCall })})
return (
...
)
}
Run Code Online (Sandbox Code Playgroud)
tbe*_*rgq 13
您仍然需要在功能组件上定义navigationOptions。您可以这样做:
export default function SomeFunctionalComponent({ navigation }) {
useEffect(() => {
navigation.setParams({
headerTitle: someVariableThatComesFromExternalCall
})
}, [])
}
SomeFunctionalComponent.navigationOptions = ({ navigation }) => {
return {
title: navigation.getParam('headerTitle'),
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*enz 10
我怀疑接受的答案不适用于当前最新版本的反应导航(5),并且它绝对不适用于此版本,因此这是 @react-navigation/native v5.7.2 的工作示例:
export default function SomeFunctionalComponent({ navigation }) {
useLayoutEffect(() => {
navigation.setOptions({
headerTitle: 'some other title',
})
}, [])
}
Run Code Online (Sandbox Code Playgroud)
我用它来访问反应上下文 - 获取用户的名字和头像,这样我就可以为他们设置一个漂亮的标题栏。我已经粘贴了代码,以防它对任何人有帮助:
import React, { useContext, useLayoutEffect } from 'react';
import UserContext from '../context/UserContext';
const HomeScreen = ({ navigation }) => {
const userContext = useContext(UserContext);
useLayoutEffect(() => {
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
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1850 次 |
| 最近记录: |