reactjs - 如何设置浏览器标签标题并添加图标
问题描述
我正在使用反应导航,并看到 chrome 浏览器选项卡标题被设置为特定导航屏幕的名称。反正有没有将标题覆盖到其他东西,也许还添加一个图标?
我确实看到我可以更改导航器屏幕名称,但是每个名称都必须是唯一的,并且我希望浏览器标题只是一个静态值,而不是在屏幕之间更改。
谢谢
解决方案
是的,你可以做到这一切:
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 - 在浏览器标签标题中添加一个图标
我怀疑有没有办法使用反应原生库来做到这一点。希望 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下面的屏幕截图中的图标):
推荐阅读
- python - 如何更快地加载 api 响应并在 pandas 中使用它在 django 中进行分析?
- apache-karaf - Opendaylight Karaf 在安装引导功能时出错
- twig - 如何在树枝模板中剥离 html 标签但保留具有特定属性的相同标签?
- r - 如何稍微修改 R 代码以便保存多个图像而不是一个?
- mongodb - 我可以在 mongo db 查询中解析 JSON 吗?
- html - 图片不可点击
- javascript - X 按钮不会关闭主导航,为什么 CSS 的“显示”不会改变?
- .htaccess - 错误 403 禁止访问从本地服务器切换到实时服务器(Windows)
- swift - 如何以编程方式正确设置 UISegmentedController 和 imageView?
- vert.x - vert.x 非阻塞和线程模型