我想为我的React应用程序设置文档标题(在浏览器标题栏中)。我已经尝试使用反应文档标题(似乎过时了),并设置document.title在constructor与componentDidMount()这些解决方案的工作- 。
Answers:
您可以使用React Helmet:
import React from 'react'
import { Helmet } from 'react-helmet'
const TITLE = 'My Page Title'
class MyComponent extends React.PureComponent {
  render () {
    return (
      <>
        <Helmet>
          <title>{ TITLE }</title>
        </Helmet>
        ...
      </>
    )
  }
}
    import React from 'react'
import ReactDOM from 'react-dom'
class Doc extends React.Component{
  componentDidMount(){
    document.title = "dfsdfsdfsd"
  }
  render(){
    return(
      <b> test </b>
    )
  }
}
ReactDOM.render(
  <Doc />,
  document.getElementById('container')
);
这对我有用。
编辑:如果您使用的是webpack-dev-server,请将内联设置为true
正如其他人所说,你可以使用document.title = 'My new title'并作出反应头盔更新页面标题。在加载脚本之前,这两种解决方案仍将呈现初始的“ React App”标题。
如果使用的create-react-app是初始文档标题,则在<title>标记/public/index.html文件中设置。
您可以直接对其进行编辑,也可以使用将由环境变量填充的占位符:
/.env:
REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...
如果出于某种原因我想要在开发环境中使用其他标题-
/.env.development:
REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...
/public/index.html:
<!DOCTYPE html>
<html lang="en">
    <head>
         ...
         <title>%REACT_APP_SITE_TITLE%</title>
         ...
     </head>
     <body>
         ...
     </body>
</html>
这种方法还意味着我可以使用全局process.env对象从应用程序中读取网站标题环境变量,这很不错:
console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!
请参阅:添加自定义环境变量
您应该在'componentWillMount'的生命周期中设置文档标题:
componentWillMount() {
    document.title = 'your title name'
  },
    React Portal可以让您渲染到根React节点之外的元素(例如<title>),就好像它们是实际的React节点一样。因此,现在您可以干净地设置标题,而无需任何其他依赖项:
这是一个例子:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Title extends Component {
    constructor(props) {
        super(props);
        this.titleEl = document.getElementsByTagName("title")[0];
    }
    render() {
        let fullTitle;
        if(this.props.pageTitle) {
            fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
        } else {
            fullTitle = this.props.siteTitle;
        }
        return ReactDOM.createPortal(
            fullTitle || "",
            this.titleEl
        );
    }
}
Title.defaultProps = {
    pageTitle: null,
    siteTitle: "Your Site Name Here",
};
export default Title;
只需将组件放入页面并设置pageTitle:
<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />
    fullTitle到index.html的内容中<title>Default Title</title>。
                    constructor!中)。从'prop-types'导入PropTypes; 从'react-dom'导入ReactDOM; const titleNode = document.getElementsByTagName(“ title”)[0]; titleNode.innerText =''; 导出默认类Title扩展React.PureComponent {static propTypes = {children:PropTypes.node,}; 构造函数(props){super(props ;; this.el = titleNode; } render(){返回ReactDOM.createPortal(this.props.children,this.el,); }}`
                    在React 16.13中,可以直接在render函数中设置它:
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
    render() {
        document.title = 'wow'
        return <p>Hello</p>
    }
}
ReactDOM.render(
    <App />,
    document.getElementById('root')
)
对于功能组件:
function App() {
    document.title = 'wow'
    return <p>Hello</p>
}
    您只需在js文件中创建一个函数并将其导出以供组件使用
如下所示:
export default function setTitle(title) {
  if (typeof title !== "string") {
     throw new Error("Title should be an string");
  }
  document.title = title;
}
并在以下任何组件中使用它:
import React, { Component } from 'react';
import setTitle from './setTitle.js' // no need to js extension at the end
class App extends Component {
  componentDidMount() {
    setTitle("i am a new title");
  }
  render() {
    return (
      <div>
        see the title
      </div>
    );
  }
}
export default App
    您可以将以下内容与 document.title = 'Home Page'
import React from 'react'
import { Component } from 'react-dom'
class App extends Component{
  componentDidMount(){
    document.title = "Home Page"
  }
  render(){
    return(
      <p> Title is now equal to Home Page </p>
    )
  }
}
ReactDOM.render(
  <App />,
  document.getElementById('root')
);
或者您可以使用此npm软件包 npm i react-document-title
import React from 'react'
import { Component } from 'react-dom'
import DocumentTitle from 'react-document-title';
class App extends Component{
  render(){
    return(
      <DocumentTitle title='Home'>
        <h1>Home, sweet home.</h1>
      </DocumentTitle>
    )
  }
}
ReactDOM.render(
  <App />,
  document.getElementById('root')
);
快乐编码!
我还没有对它进行过彻底的测试,但这似乎可行。用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节点。
您可以使用ReactDOM和更改<title>标签
ReactDOM.render(
   "New Title",
   document.getElementsByTagName("title")[0]
);
    我使用了这种方法,后来发现了它,因为它对我来说比较容易。我将其与功能组件结合使用。 仅当您不关心用户禁用页面上的Javascript时它不会显示任何标题时,才执行此操作。
您需要做两件事。
1.进入您的index.html并在此处删除此行
<title>React App</title>
2.进入mainapp函数并返回它,它只是一个普通的html结构,您可以在body标签之间复制并粘贴网站的主要内容:
return (
        <html>
          <head>
            <title>hi</title>
          </head>
          <body></body>
        </html>
      );
您可以根据需要替换标题。