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

时间:2018-09-17 11:09:03

标签: reactjs

我在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>);
}

1 个答案:

答案 0 :(得分:0)

在html头中添加标签的一种方法是使用react-helmet包。它还将允许添加其他head标签。

<Helmet>
   <meta charSet="utf-8" />
   <title>My Title</title>
   <link rel="canonical" href="" />
</Helmet>