React Navigation5.x 动态修改标题内容

React Navigation

官方文档

搭建环境

# 安装全局依赖
$ npm install -g expo-cli
# 生成种子模板
expo init <projectName> [--npm]

安装 ReactNavigation

# 安装依赖
$ yarn add @react-navigation/native
# 安装依赖
$ yarn add react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
# 安装依赖
yarn add @react-navigation/stack

代码展示

options={({ route }) => ({ title: route.params?.name })} 主要通过该属性配置实现

接口文档

源码地址

  • App.js
import 'react-native-gesture-handler';
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { StyleSheet, Text, View } from 'react-native';
import { createStackNavigator } from '@react-navigation/stack';
import DetailsScreen from "./page/details"

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Details">
        <Stack.Screen name="Details" component={DetailsScreen} 
          options={({ route }) => ({ title: route.params?.name })}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;
  • details.js

navigation.setOptions({title: text}) 通过该方法动态设置标题

源码地址

import React from 'react';
import { StyleSheet, TextInput, Text, View } from 'react-native';

export default function DetailsScreen({navigation}) {
  const {setOptions} = navigation
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <TextInput style={styles.input} 
        onChangeText={text=>{
          setOptions({
            title: text
        })
      }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  input: {
    width: 200,
    height:50,
    backgroundColor: '#ccc'
  }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值