如何从屏幕更新导航标题?

问题描述

react-native version 0.62

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...