React中的document.title(静态页面)

问题描述 投票:0回答:1

我在React中有两个“静态”页面:“关于”和“条款和条件”。他们没有任何国家或道具。

在显示这些页面时,呈现document.title的最佳方法是什么?

我正在使用功能无状态组件,所以没有componentDidMount

export default function About() {
  return (<article>
          <h1>About us</h1>
            <p>Lorem ipsum dolor sit amet</p>
          </div>
          </article>);
}

在一个网站上建议在返回声明之前使用document.title = "About",如下所示。由于功能组件可以被认为具有隐式render()render()应该是纯函数(它不与浏览器交互),而不是最佳解决方案。

export default function About() {
  document.title = "About";
  return (<article>
          <h1>About us</h1>
            <p>Lorem ipsum dolor sit amet</p>
          </div>
          </article>);
}

是否有意义使用另一个使用<WindowTitle title="About" />来修改窗口标题的类组件componentDidMount,并在功能组件中使用该组件?还是有更好的解决方案?

class WindowTitle extends Component() {
    constructor(props) {
        super(props)
    }
    componentDidMount() {
        document.title = this.props.title;
    }
}

function About() {
  return (<article>
          <WindowTitle title="About" />
            <h1>About us</h1>
            <p>Lorem ipsum dolor sit amet</p>
          </div>
          </article>);
}
reactjs
1个回答
0
投票

在html的头部添加标签的方法之一是使用react-helmet包。它还允许添加其他头标记。

<Helmet>
   <meta charSet="utf-8" />
   <title>My Title</title>
   <link rel="canonical" href="" />
</Helmet>
© www.soinside.com 2019 - 2024. All rights reserved.