itsource

React에서 문서 제목을 설정하려면 어떻게 해야 합니까?

mycopycode 2023. 1. 28. 09:35
반응형

React에서 문서 제목을 설정하려면 어떻게 해야 합니까?

React 어플리케이션의 문서 제목(브라우저 제목 바)을 설정하고 싶습니다.react-document-title(최신 버전이 아닌 것 같음)을 사용하여 설정을 시도했습니다.document.title constructor ★★★★★★★★★★★★★★★★★」componentDidMount() - 이 해결책들은 효과가 없습니다.

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로 인라인으로 설정하는 경우

React 16.8+의 경우 기능 구성요소에서 Effect Hook을 사용할 수 있습니다.

import React, { useEffect } from 'react';

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


하려면 , 「」를 한다.<title>선언적인 방법으로 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>
        ...
      </>
    )
  }
}

React 16.8의 경우 useEffect를 사용하여 함수 성분으로 이 작업을 수행할 수 있습니다.

예:

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

가 한되므로 useEffect와 합니다.componentDidMount.

이 말씀하신 것처럼 ''라는 표현을 쓸 수 요.document.title = 'My new title' Respect Helmet을 눌러 페이지 제목을 업데이트합니다.두 솔루션 모두 스크립트를 로드하기 전에 초기 'React App' 제목을 계속 렌더링합니다.

「 」를 사용하고 create-react-app 번째 문서 제목은<title> 부착/public/index.htmlfilename을 클릭합니다.

이를 직접 편집하거나 환경변수로 채워지는 자리 표시자를 사용할 수 있습니다.

/.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!

참조: 커스텀 환경 변수 추가

React 16.8.을 통해 커스텀 훅을 구축할 수 있습니다(@Shortchange의 솔루션과 유사).

export function useTitle(title) {
  useEffect(() => {
    const prevTitle = document.title
    document.title = title
    return () => {
      document.title = prevTitle
    }
  })
}

이는 모든 반응 구성 요소에 사용할 수 있습니다. 예:

const MyComponent = () => {
  useTitle("New Title")
  return (
    <div>
     ...
    </div>
  )
}

구성 요소가 마운트되는 즉시 제목을 업데이트하고 마운트 해제 시 이전 제목으로 되돌립니다.

import React from 'react';

function useTitle(title: string): void => {
  React.useEffect(() => {
    const prevTitle = document.title;
    document.title = title;

    return () => {
      document.title = prevTitle;
    };
  }, []);
}

function MyComponent(): JSX.Element => {
  useTitle('Title while MyComponent is mounted');

  return <div>My Component</div>;
}

이것은 꽤 간단한 해결책입니다.useTitle문서 제목을 설정하고 구성 요소가 마운트 해제되면 이전 상태로 재설정됩니다.

리액트 포털을 사용하여 루트 리액트 노드 외부에 있는 요소에 렌더링할 수 있습니다(예:<title>이치노따라서 제목을 더 이상 의존하지 않고 깔끔하게 설정할 수 있습니다.

다음은 예를 제시하겠습니다.

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} />

궁금한 경우 렌더링 기능 내에서 직접 설정할 수 있습니다.

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>
}

그러나 이는 렌더링을 차단하기 때문좋지 않은 방법입니다(먼저 렌더링을 우선시하십시오).

베스트 프랙티스:

클래스 컴포넌트:

class App extends React.Component {
    // you can also use componentDidUpdate() if the title is not static
    componentDidMount(){
        document.title = "good"
    }

    render() {
        return <p>Hello</p>
    }
}

기능 컴포넌트

function App() {
    // for static title, pass an empty array as the second argument
    // for dynamic title, put the dynamic values inside the array
    // see: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
    useEffect(() => {
        document.title = 'good'
    }, []);

    return <p>Hello</p>
}

componentWillMount'의 라이프 사이클에서 문서 제목을 설정해야 합니다.

componentWillMount() {
    document.title = 'your title name'
  },

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

는 여러 할 수 .React Helmet 갈고리를 때 훅을 사용해서 를 만들기도 합니다.useEffect 여러분만의 말고 '갈고리로 하다'의 를 쓸 react-use:

리액트 헬멧

import React from 'react';
import { Helmet } from 'react-helmet';

const MyComponent => () => (
  <Helmet>
    <title>My Title</title>
  </Helmet>
)

반응 사용

import React from 'react';
import { useTitle } from 'react-use';

const MyComponent = () => {
  useTitle('My Title');

  return null;
}

헬멧은 정말 좋은 방법이지만 제목만 바꾸면 되는 앱은 다음과 같습니다. (현대식 리액트 솔루션 - 후크 사용)

  1. 변경 페이지 제목 구성 요소 생성
import React, { useEffect } from "react";

const ChangePageTitle = ({ pageTitle }) => {
  useEffect(() => {
    const prevTitle = document.title;
    document.title = pageTitle;
    return () => {
      document.title = prevTitle;
    };
  });

  return <></>;
};

export default ChangePageTitle;
  1. 컴포넌트 사용
import ChangePageTitle from "../{yourLocation}/ChangePageTitle";

...

return (
    <>
      <ChangePageTitle pageTitle="theTitleYouWant" />
      ...
    </>
  );

...

는 '하다'와 함께 할 수 .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에 inside inside inside render()다이나믹한 타이틀이 필요한 경우는, 갱신/최신 상태를 유지할 수 있습니다.마운트 해제 시 제목도 되돌려야 합니다.포털은 귀엽지만 불필요해 보입니다.기노 dom dom DOM 。

React v18+에서는 커스텀 훅이 가장 심플한 방법입니다.

순서 1: 후크를 작성합니다.(후크/사용문서)Title.js)

import { useEffect } from "react";
export const useDocumentTitle = (title) => {

    useEffect(() => {
        document.title = `${title} - WebsiteName`;
    }, [title]);

    return null;
}

스텝 2: 페이지에 따라 커스텀타이틀을 붙여 모든 페이지에서 후크를 호출합니다.(페이지/홈페이지.js)

import { useDocumentTitle } from "../hooks/useDocumentTitle";

const HomePage = () => {
    useDocumentTitle("Website Title For Home Page");
    
    return (
        <>           
            <main>
                <section>Example Text</section>
            </main>            
        </>
    );
}

export { HomePage };

동적인 페이지에서도 기능합니다.제품 제목이나 표시할 콘텐츠를 전달하기만 하면 됩니다.

및 React DOM 을 사용할 수 .<title> 부착

ReactDOM.render(
   "New Title",
   document.getElementsByTagName("title")[0]
);

가장 쉬운 방법은 react-module-configuration을 사용하는 것입니다.

npm install react-document-configuration --save

예:

import React from "react";
import Head from "react-document-configuration";

export default function Application() {
    return (
        <div>
            <Head title="HOME" icon="link_of_icon" />
            <div>
                <h4>Hello Developers!</h4>
            </div>
        </div>
    );
};```
const [name, setName] = useState("Jan");
  useEffect(() => 
    {document.title =   "Celebrate " +  {name}.name  ;}
  );
  

FAQ 페이지에 페이지 제목을 사용하고 싶었습니다.그래서 리액트 헬메트를 사용했습니다.

먼저 npm i react-helmet을 사용하여 react-helmet을 설치했습니다.

그리고 반품 안에 다음과 같은 태그를 추가했습니다.

에서 
react-helmet에서 {}
PAGE_는 PAGE_입니다.= ' 페이지 = 'FAQ 페이지'
컴포넌트 {\}(\)를 합니다.
렌더링() {
반환(
{페이지_제목 } 이것은 나의 FAQ 페이지입니다.

) }}

초보자라면 리액트 프로젝트 폴더의 공용 폴더로 이동하여 제목을 "index.html"로 편집하여 저장함으로써 이 모든 것에서 자신을 구할 수 있습니다.잊지 말고 저장해 두면 반영이 됩니다.

언급URL : https://stackoverflow.com/questions/46160461/how-do-you-set-the-document-title-in-react

반응형