【发布时间】:2020-07-28 14:54:25
【问题描述】:
我正在使用react navigation 并看到 chrome 浏览器选项卡标题被设置为特定导航屏幕的名称。有没有办法把标题改成别的东西,也许还加个图标?
我确实看到我可以更改导航器的屏幕名称,但是每个名称都必须是唯一的,并且我希望浏览器标题只是一个静态值,而不是在屏幕之间更改。
谢谢
【问题讨论】:
标签: reactjs browser tabs navigation native
我正在使用react navigation 并看到 chrome 浏览器选项卡标题被设置为特定导航屏幕的名称。有没有办法把标题改成别的东西,也许还加个图标?
我确实看到我可以更改导航器的屏幕名称,但是每个名称都必须是唯一的,并且我希望浏览器标题只是一个静态值,而不是在屏幕之间更改。
谢谢
【问题讨论】:
标签: reactjs browser tabs navigation native
是的,你可以做到这一切:
1 - 添加浏览器标签标题并保留导航标题
在下面的这个例子中,我使用了来自 "@react-navigation/stack" 的 createStackNavigator 函数:
const Stack = createStackNavigator();
function Navigator() {
return (
<NavigationContainer>
- <Stack.Navigator >
+ <Stack.Navigator screenOptions={{ title: "My application name here" }}>
<Stack.Screen
name="Home"
+ options={{ headerTitle: "My Home" }}
component={HomeScreen} />
<Stack.Screen
name="Details"
+ options={{ headerTitle: "My Details" }}
component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default Navigator;
2 - 在浏览器标签标题中添加图标
我怀疑有没有办法使用 react 原生库来做到这一点。希望 javascript “文档”对象在 React 中可用,所以我们可以通过这种方式将图标添加到浏览器选项卡:
export default function App() {
+ // On android and iOS, trying this block of code will fail and go to the catch block.
+ try {
+ // Select the <head> tag under <body>
+ const headTag = document.querySelector("head");
+ // Create the <link/> tag.
+ const icon = document.createElement("link");
+ // Create the rel="" attribute
+ const attributeRel = document.createAttribute("rel");
+ // Assign the value "icon" to the rel attribute so that attributeRel becomes rel="icon"
+ attributeRel.value = "icon";
+ // Create the href="" attribute
+ const attributeHref = document.createAttribute("href");
+ // Assign your application icon path to the href attribute so that attributeHref becomes href="path/to/my/icon"
+ attributeHref.value =
+ "path/to/my/icon";
+ // Set the rel attibute to <link> so that the icon JS object becomes <link rel="icon"/>
+ icon.setAttributeNode(attributeRel);
+ // Set the href attibute to <link> so that the icon JS object becomes <link rel="icon" href="path/to/my/icon"/>
+ icon.setAttributeNode(attributeHref);
+ // Insert the <link [...] /> tag into the <head>
+ headTag.appendChild(icon);
+ } catch (e) {
+ //Browser tabs do not exist on android and iOS, so let's just do nothing here.
+ }
return <Navigator />;
}
这里是结果的一些屏幕截图(“path/to/my/icon”已替换为“https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico”,以便您请参阅下面屏幕截图中的 stackoverflow 图标):
【讨论】: