30秒学会 React 片段 · 2023年5月16日

30秒学会 React 片段 – React useTitle hook

Sets the title of the page

  • Use typeof to determine if the Document is defined or not.
  • Use the useRef() hook to store the original title of the Document, if defined.
  • Use the useEffect() hook to set Document.title to the passed value when the component mounts and clean up when unmounting.

代码实现

const useTitle = title => {
  const documentDefined = typeof document !== 'undefined';
  const originalTitle = React.useRef(documentDefined ? document.title : null);

  React.useEffect(() => {
    if (!documentDefined) return;

    if (document.title !== title) document.title = title;

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

使用样例

const Alert = () => {
  useTitle('Alert');
  return <p>Alert! Title has changed</p>;
};

const MyApp = () => {
  const [alertOpen, setAlertOpen] = React.useState(false);

  return (
    <>
      <button onClick={() => setAlertOpen(!alertOpen)}>Toggle alert</button>
      {alertOpen && <Alert />}
    </>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <MyApp />
);

翻译自:https://www.30secondsofcode.org/react/s/use-title