您如何在React中设置文档标题?

React.js

前端L小小

2020-03-16

我想为我的React应用程序设置文档标题(在浏览器标题栏中)。我已经尝试使用反应文档标题(似乎过时了),并设置document.titleconstructorcomponentDidMount()这些解决方案的工作- 。

第1722篇《您如何在React中设置文档标题?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
Jim老丝猪猪 2020.03.16

如果您是初学者,则可以通过进入react project文件夹的公共文件夹并在“ index.html”中编辑标题并将其放在您自己的文件夹中,从而摆脱所有麻烦。不要忘记保存,它会反映出来。

小小 2020.03.16

我还没有对它进行彻底的测试,但这似乎可行。用TypeScript编写。

interface Props {
    children: string|number|Array<string|number>,
}

export default class DocumentTitle extends React.Component<Props> {

    private oldTitle: string = document.title;

    componentWillUnmount(): void {
        document.title = this.oldTitle;
    }

    render() {
        document.title = Array.isArray(this.props.children) ? this.props.children.join('') : this.props.children;
        return null;
    }
}

用法:

export default class App extends React.Component<Props, State> {

    render() {
        return <>
            <DocumentTitle>{this.state.files.length} Gallery</DocumentTitle>
            <Container>
                Lorem ipsum
            </Container>
        </>
    }
}

不知道为什么其他人热衷于将整个应用程序放入<Title>组件中,这对我来说很奇怪。

通过更新document.title内部render()内容,如果您需要动态标题,它将刷新/保持最新状态。卸载后,它也应该还原标题。门户网站很可爱,但似乎没有必要。我们实际上不需要在这里操纵任何DOM节点。

理查德村村小宇宙 2020.03.16

您可以使用ReactDOM和更改<title>标签

ReactDOM.render(
   "New Title",
   document.getElementsByTagName("title")[0]
);
小卤蛋猪猪 2020.03.16

对于React 16.8,您可以使用useEffect对功能组件进行此操作

例如:

useEffect(() => {
   document.title = "new title"
}, []);

将第二个参数作为数组使用时,只会调用一次useEffect,使其类似于componentDidMount

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android