【发布时间】:2019-05-20 07:59:38
【问题描述】:
我想根据一些属性更改 Reacjs 应用程序的 favicon。我已经将图标保存在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 中更改 favicon 的最佳方法是什么(我搜索了很多但没有找到任何答案)。
第二:我应该如何定义href。
【问题讨论】:
-
错误
Cannot read property 'id' of undefined表示project未定义。未定义的原因未显示。 -
@estus :D 是的,谢谢。我当时心情很生气,为什么路径不起作用,没有得到
id与项目对象有关