内置浏览器 <title> 组件允许你指定文档的标题。

🌐 The built-in browser <title> component lets you specify the title of the document.

<title>My Blog</title>

参考

🌐 Reference

<title>

要指定文档的标题,请渲染 内置浏览器 <title> 组件。你可以从任何组件渲染 <title>,React 将始终将对应的 DOM 元素放置在文档头部。

🌐 To specify the title of the document, render the built-in browser <title> component. You can render <title> from any component and React will always place the corresponding DOM element in the document head.

<title>My Blog</title>

查看更多示例。

属性

🌐 Props

<title> 支持所有 常用元素属性

  • children<title> 只接受文本作为子元素。此文本将成为文档的标题。你也可以传入你自己的组件,只要它们只渲染文本即可。

特殊渲染行为

🌐 Special rendering behavior

React 将始终将对应于 <title> 组件的 DOM 元素放置在文档的 <head> 内,无论它在 React 树中的渲染位置如何。<head><title> 在 DOM 中存在的唯一有效位置,但如果表示特定页面的组件可以自己渲染其 <title>,这既方便又保持了组合性。

🌐 React will always place the DOM element corresponding to the <title> component within the document’s <head>, regardless of where in the React tree it is rendered. The <head> is the only valid place for <title> to exist within the DOM, yet it’s convenient and keeps things composable if a component representing a specific page can render its <title> itself.

有两个例外:

🌐 There are two exception to this:

  • 如果 <title> 位于 <svg> 组件中,则没有特殊行为,因为在此上下文中它并不表示文档的标题,而是 该 SVG 图形的辅助功能注释
  • 如果 <title> 有一个 itemProp 属性,没有特殊行为,因为在这种情况下它并不表示文档的标题,而是表示页面特定部分的元数据。

易犯错误

一次只能渲染一个 <title>。如果多个组件同时渲染 <title> 标签,React 会将所有这些标题放入文档头部。当发生这种情况时,浏览器和搜索引擎的行为是不确定的。

🌐 Only render a single <title> at a time. If more than one component renders a <title> tag at the same time, React will place all of those titles in the document head. When this happens, the behavior of browsers and search engines is undefined.


用法

🌐 Usage

设置文档标题

🌐 Set the document title

从任何组件渲染 <title> 组件,并将文本作为其子元素。React 会在文档 <head> 中放置一个 <title> DOM 节点。

🌐 Render the <title> component from any component with text as its children. React will put a <title> DOM node in the document <head>.

import ShowRenderedHTML from './ShowRenderedHTML.js';

export default function ContactUsPage() {
  return (
    <ShowRenderedHTML>
      <title>My Site: Contact Us</title>
      <h1>Contact Us</h1>
      <p>Email us at support@example.com</p>
    </ShowRenderedHTML>
  );
}

在标题中使用变量

🌐 Use variables in the title

<title> 组件的子元素必须是单个文本字符串。(或者是单个数字,或者是具有 toString 方法的单个对象。)这可能不太明显,但像这样使用 JSX 大括号:

🌐 The children of the <title> component must be a single string of text. (Or a single number or a single object with a toString method.) It might not be obvious, but using JSX curly braces like this:

<title>Results page {pageNumber}</title> // 🔴 Problem: This is not a single string

… 实际上会导致 <title> 组件的子元素变成一个包含两个元素的数组(字符串 "Results page"pageNumber 的值)。这将导致错误。相反,应使用字符串插值向 <title> 传递一个单独的字符串:

<title>{`Results page ${pageNumber}`}</title>