【发布时间】:2020-09-05 18:50:56
【问题描述】:
对不起,标题的措辞不好,我在功能组件中使用 react-navigation 的 navigationOptions 有问题,我正在使用自定义挂钩进行主题化。 我正在包装组件,然后使用 withTheme 钩子。
问题本身就是无论我如何使用 navigationOptions,它都不会改变标题
这是我遇到困难的组件:
HomeScreen = ({ theme }) => {
return (
...
);
};
HomeScreen.navigationOptions = {
title: 'Dashboard',
headerTintColor: 'white',
headerStyle: {
borderBottomWidth: 0,
backgroundColor: 'red',
},
headerLeft: (
<TouchableOpacity
style={{ paddingLeft: 15 }}
onPress={() => navigation.dispatch(DrawerActions.toggleDrawer())}
>
<Feather name="arrow-left" size={24} color="#ffffff" />
</TouchableOpacity>
),
headerRight: (
<View style={{ flexDirection: 'row' }}>
</View>
),
}
const style = StyleSheet.create({
...
}
});
export default withTheme(HomeScreen);
还有themeProvider组件
const STORAGE_KEY = 'THEME_ID';
const ThemeContext = React.createContext();
export const ThemeContextProvider = ({ children }) => {
const [themeID, setThemeID] = useState();
useEffect(() => {
(async () => {
const storedThemeID = await AsyncStorage.getItem(STORAGE_KEY);
if (storedThemeID) setThemeID(storedThemeID);
else setThemeID(THEMES[1].key);
})();
}, []);
return (
<ThemeContext.Provider value={{ themeID, setThemeID }}>
{!!themeID ? children : null}
</ThemeContext.Provider>
);
};
export function withTheme(Component) {
return props => {
const { themeID, setThemeID } = useContext(ThemeContext);
const getTheme = themeID => THEMES.find(theme => theme.key === themeID);
const setTheme = themeID => {
AsyncStorage.setItem(STORAGE_KEY, themeID);
setThemeID(themeID);
};
return (
<Component
{...props}
themes={THEMES}
theme={getTheme(themeID)}
setTheme={setTheme}
/>
);
};
}
谁能告诉我我错过了什么?
【问题讨论】:
-
headerLeft 和 headerRight 可以是函数,使它们动态化吗?
-
据我所知,问题不在于 headerLeft 和 headerRight,因为我试图删除它们并且标题仍然不会进行任何更改,删除 withTheme 钩子会呈现正确的标题,但我'不完全确定在 themeProvider 组件中可以做些什么不同的事情。
-
也许this GitHub issue 可能会有所帮助。 v3 解决方案已将
navigationOptions变成了一个函数! (我是通过googling around 找到的。)
标签: react-native react-navigation