0
react-native version 0.62

我正在制作一个测验应用程序,并且在每个新问题(一个新测验屏幕,QuestionScreen.js)上,我想更新导航栏中的标签,该标签在App.js In中声明App.js,这里的问题是我不知道如何将状态传递questionIndexHomeScreen或者QuestionScreen,通常我认为这将使用像<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

function QuestionScreen({route, navigation, options}) {

    const { pageIndex } = route.params;

[github上的完整代码] https://github.com/liaoxsong/expofirst 我是react-native的新手,我来自原生移动开发,这个Stack.Navigator api看起来很奇怪,我不能只管理导航屏幕组件本身的标题?那会让事情变得更容易。

4

2 回答 2

0

您应该使用上下文或 redux,上下文示例:

页面上下文.js

export const PageContext= React.createContext();

应用程序.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

于 2020-09-15T05:30:28.187 回答
0

很难自定义反应导航给出的默认标题,您可以做的是禁用标题并创建自己的自定义标题。

通过在 createStackNavigator 中提供 prop headerMode={"none"} 来禁用标头,并在顶部放置您自己的自定义标头,

禁用标题文档:https ://reactnavigation.org/docs/stack-navigator/#headermode

于 2020-09-15T02:19:01.623 回答