Reactjs,更改 componentDidMount 中的图标

Reactjs, change the favicon in componentDidMount

我想根据某些属性更改 Reacjs 应用程序的图标。我已经将图标保存在 public 文件夹中,但找不到将路径作为 href 提供给新创建的元素的方法。

  componentDidMount() {
    const { project } = this.props.rootStore!;
    let link = document.createElement('link');
    const oldLink = document.getElementById('favicon');
    link.id = 'favicon';
    link.rel = 'shortcut icon';
    link.href = // here I tried the following string literals
    if (oldLink) {
      document.head.removeChild(oldLink);
    }
    document.head.appendChild(link);
  }

link.href='%PUBLIC_URL%/assets/images/' + project.id + '/favicon.ico';
// TypeError: Cannot read property 'id' of undefined

link.href = `%PUBLIC_URL%/assets/images/${project.id}/favicon.ico`;
// TypeError: Cannot read property 'id' of undefined

link.href = '%PUBLIC_URL%/assets/images/${project.id}/favicon.ico';
// GET http://localhost:3000/demo/category/showroom/%PUBLIC_URL%/assets/images/$%7Bproject.id%7D/favicon.ico 400 (Bad Request)

现在我的问题可以是第一个:在 Reacjs 中更改网站图标的最佳方法是什么(我搜索了很多但没有找到任何答案)。 第二:我应该如何定义 href.

没有最好的方法来做到这一点。 React 不提供处理应用程序外部现有 DOM 元素的功能。这应该在 React 中完成,就像在 vanilla JavaScript:

中一样
let link = document.querySelector('link[rel="shortcut icon"]') ||
  document.querySelector('link[rel="icon"]');

if (!link) {
    link = document.createElement('link');
    link.id = 'favicon';
    link.rel = 'shortcut icon';
    document.head.appendChild(link);
}

link.href = `/assets/images/${id}/favicon.ico`;

href 最好包含绝对路径或 URL 以提供正确的图标位置,而不管基础 URL.

一种 React-y 方法是使用 react-helmet

使用该库,您可以更改 <head>

中的元素

例如

import Helmet from 'react-helmet'

...

<Helmet>
  <title>ABC</title>
  <meta name="ABC" content: "ABC" />
  <link rel="icon" type="image/png" href="favicon.ico" sizes="16x16" />
</Helmet>

npm install react-meta-tags --save

https://github.com/s-yadav/react-meta-tags

在我的项目中对此感到非常满意。 Helmet 是另一种选择。

import React from 'react';
import MetaTags from 'react-meta-tags';

class Component1 extends React.Component {
  render() {
    return (
        <div className="wrapper">
          <MetaTags>
            <title>Page 1</title>
            <meta name="description" content="Some description." />
            <meta property="og:title" content="MyApp" />
            <meta property="og:image" content="path/to/image.jpg" />
          </MetaTags>
          <div className="content"> Some Content </div>
        </div>
      )
  }
}