问题描述
react-native version 0.62
我正在制作一个测验应用程序,并且在每个新问题(一个新的测验屏幕QuestionScreen.js
)上,我想更新App.js
中声明的导航栏中的标签
在App.js
中,这里的问题是我不知道如何将状态questionIndex
传递给HomeScreen
或QuestionScreen
,通常我认为这将使用{{ 1}}。我试图在<Question questionIndex={questionIndex}>
中传递它们,但这似乎不起作用...
options
在const App = () => {
const [questionIndex,setQuestionIndex] = useState(0);
return (
<NavigationContainer>
<Stack.Navigator initialRouteName='Home'
>
<Stack.Screen
name='Home'
component={HomeScreen}
options={{
title:''
}}
/>
<Stack.Screen
name='QuestionScreen'
component={QuestionScreen}
options={({ navigation }) => ({
headerBackTitleVisible: false,headerRight: ()=>(<HeaderRight pageIndex={questionIndex}/>),headerRightContainerStyle: {
alignItems: "flex-end",paddingRight: 25
},})}
/>
function HeaderRight(props) {
return (
<Text>{props.pageIndex}/{questions.length-1}</Text>
);
}
const HomeScreen = ({ navigation }) => {
return (
<View style={styles.container} >
<ScrollView>
<TouchableOpacity onPress={()=>
//here I'm unable to retrieve the questionIndex props.
//tried navigation.getParams("questionIndex") or route.params
navigation.navigate('QuestionScreen',{
pageIndex: 0
})
}>
QuestionScreen.js
[完整代码在github上] https://github.com/liaoxsong/expofirst 我是本机反应的新手,来自本地移动开发,此Stack.Navigator api看起来很怪异,我不能仅从屏幕组件本身管理导航标题吗?这样会使事情变得容易。
解决方法
您应该使用context或redux,例如context:
page-context.js
export const PageContext= React.createContext();
app.js
const App = () => {
const [questionIndex,setQuestionIndex] = useState(0);
return(
<PageContext.Provider value={[questionIndex,setQuestionIndex]}>
<NavigationContainer> // your routes
</PageContext.Provider>)
QuestionScreen.js
https://reactnavigation.org/docs/header-buttons/
function QuestionScreen({route,navigation,options}) {
const [questionIndex] = useContext(PageContext);
React.useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<HeaderRight pageIndex={questionIndex}/>
),});
},[navigation,questionIndex]);
}
用户可以使用setQuestionIndex在所需的每个屏幕中更改questionIndex
,很难自定义反应导航给出的默认标题,您可以做的就是禁用标题并创建自己的自定义标题。
通过在createStackNavigator中提供prop headerMode = {“ none”}来禁用标题,并在顶部具有您自己的自定义标题,
禁用标题文档:https://reactnavigation.org/docs/stack-navigator/#headermode