【问题标题】:react changing page title响应更改页面标题
【发布时间】:2018-12-07 19:45:23
【问题描述】:

我知道我可以使用react-document-title 和react-helmet 来更改页面标题。但我有一个问题。

react-document-title 可以设置默认页面标题如:

function App() {
  // Use "My Web App" if no child overrides this
  return (
    <DocumentTitle title='My Web App'>
      <SomeRouter />
    </DocumentTitle>
  );
}

react-helmet 可以做同样的事情吗?

另外,从github中的例子来看,它们都使用了静态标题。他们可以做像 youtube 这样标题不是静态的事情吗?

如果您在 youtube 主页,页面标题显示 Youtube。
如果您正在观看视频,页面标题会显示视频的名称,并带有-youtube。

显然,- youtube 是静态的,而视频的名称是动态的。

目标是我想在router.js中设置默认标题(如react-document-title),然后如果组件需要标题(默认标题加上组件的页面标题),更改页面标题。如果不需要,则使用以下代码使用默认标题:

function App() {
  // Use "My Web App" if no child overrides this
  return (
    <DocumentTitle title='My Web App'>
      <Router path="/" component={Home} />
    </DocumentTitle>
  );
}

function HomePage() {
  // Use "Home" while this component is mounted
  return (
    //trying to do something like this
    <DocumentTitle title='${default title } -Home'>
      // output: My Web App - Home
      <h1>Home, sweet home.</h1>
    </DocumentTitle>
  );
}

你能展示这个例子吗,因为我需要它来理解这一点?

【问题讨论】:

    标签: react-router react-helmet


    【解决方案1】:

    您可以尝试document.title 更改页面标题,如下代码所示。

    import React from 'react';
    
    const DemoComponent= () => {
      document.title = "This is demo Component";
      return (
        <div className="container">
          <div className="row">
            <h1> My Component</h1>
          </div>
        </div>
      );
    }
    
    export default DemoComponent;
    

    这里我设置了页面的标题“这是演示组件”。所以,当这个组件被渲染时,页面的标题会发生变化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 2015-11-27
      • 1970-01-01
      • 2020-04-05
      相关资源
      最近更新 更多