【问题标题】:In reactjs how to change the Page title as same as the page route link name?在 reactjs 中如何将页面标题更改为与页面路由链接名称相同?
【发布时间】:2019-08-17 14:27:46
【问题描述】:

在 Reactjs 中,如何动态更改页面标题。例如:当我们重定向到新页面时,新页面路由行应该作为页面标题

例如:如果主页,则磁贴应为 xxx 主页,如果在联系页面中,则标题应为 xxx 联系

【问题讨论】:

标签: reactjs


【解决方案1】:

你可以使用 Hooks,在改变状态时你可以使用它的useEffect() 方法。

例如,

import React, { useState, useEffect } from 'react';

const Example = () => {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

选自React Hooks documentation

【讨论】:

    【解决方案2】:

    试试这个。

     import React from 'react'
     import ReactDOM from 'react-dom'
    
    
     class TestPage extends React.Component{
       componentDidMount(){
        document.title = "Test page title"
       }
    
        render(){
         return(
          <p> hello world! </p>
         );
        }
      }
    
      ReactDOM.render(
        <TestPage/>,
        document.getElementById('root')
      );
    

    【讨论】:

    • 谢谢...这个正在工作,但我不想这样。我有 250 多页。所以它不可能去每一页并给出标题。这就是为什么我要求将链接名称作为页面标题。希望你能理解我的需要!!
    猜你喜欢
    • 2018-01-09
    • 2018-06-25
    • 2016-04-08
    • 2016-06-15
    • 2021-09-12
    • 1970-01-01
    • 2021-01-13
    • 2012-01-11
    • 1970-01-01
    相关资源
    最近更新 更多