reactjs 如何为每个页面设置基于路线的动态标题?

fkvaft9z  于 2023-01-08  发布在  React
关注(0)|答案(2)|浏览(200)

应创建单独的文件,并动态更改标题,如何实现

    • 应用程序js**
export default function App() {
  return (
    <BrowserRouter>
      <Routes>
 </BrowserRouter>
  );
}
    • 路线. js**
import { useRoutes } from "react-router-dom";
const Layout = React.lazy(() => import("/Layout.jsx"));
const Blogs = React.lazy(() => import("/Blogs.jsx"));
const NoPage = React.lazy(() => import("/NoPage.jsx"));
const Routes() {
 let element = useRoutes([
    {
      path: "/",
      element: <Suspense fallback={null}><Layout /></Suspense>

    
},
 {
      path: "/",
      element:  <Suspense fallback={null}><Blogs /></Suspense>
},

{
      path: "*",
      element: <Suspense fallback={null}><NoPage /></Suspense>
},
]);

  return element;
}

根据路线,我们如何通过维护一个js文件来动态地更改每个页面的标题,以及我们如何使所有页面的徽标与标题相同

anauzrmj

anauzrmj1#

对于React 16.8+,您可以在功能组件中使用效果挂钩:

import React, { useEffect } from 'react';

function Example() {
  useEffect(() => {
    document.title = 'My Page Title';
  }, []);
}

无挂钩:

import React from 'react'
import ReactDOM from 'react-dom'

class Example extends React.Component{
  componentDidMount(){
    document.title = "My Page Title"
  }

  render(){
    return(
      <b> your data</b>
    )
  }
}

也可以将其单独设置为父零部件。

import { useEffect } from "react";

const Page = (props) => {
  useEffect(() => {
    document.title = props.title || "";
  }, [props.title]);
  return props.children;
};

export default Page;

您的路线:

<Route
      path="/about"
      render={(props) => (
        <Page title="Index">
          <Index {...props} />
        </Page>
      )}
    />
    
    <Route
      path="/profile"
      render={(props) => (
        <Page title="Profile">
          <Profile {...props} />
        </Page>
      )}
    />
ttp71kqs

ttp71kqs2#

可以为组件使用名称prop。

import { useRoutes } from "react-router-dom";
const Layout = React.lazy(() => import("/Layout.jsx"));
const Blogs = React.lazy(() => import("/Blogs.jsx"));
const NoPage = React.lazy(() => import("/NoPage.jsx"));
const Routes() {
let element = useRoutes([
{
  path: "/",
  element: <Suspense fallback={null}><Layout title="Layout Page"/></Suspense>
},
{
   path: "/",
  element:  <Suspense fallback={null}><Blogs title="Blogs Page"/></Suspense>
},
{
  path: "*",
  element: <Suspense fallback={null}><NoPage title="404 Page"/></Suspense>
},
]);

   return element;
}

相关问题