使用React头盔管理您的头脑

React Helmet是一个方便的组件,用于动态管理文档的部分,如设置标题、描述和meta标签。配合服务器端渲染,它能提升SEO和社交媒体友好性。本文介绍了其安装、基本用法、覆盖值、html和body属性以及服务器端渲染和异步渲染的方法。
摘要由CSDN通过智能技术生成

React Helmet is a simple component that makes it easy to manage and dynamically set what’s in the document’s head section. For example, you can use React Helmet to set the title, description and meta tags for the document.

React Helmet是一个简单的组件,可以轻松管理和动态设置文档头部的内容。 例如,您可以使用React Helmet设置文档的标题,描述和meta标签。

It comes-in especially handy when combined with server-side rendering because it allows to set meta tags that will be read by search engines and social media crawlers. This makes server-side rendering and React Helmet a dynamic duo for creating apps that are SEO and social media friendly.

服务器端渲染结合使用时,它特别方便,因为它允许设置将由搜索引擎和社交媒体抓取工具读取的元标记。 这使得服务器端渲染和React Helmet成为动态二人组,用于创建SEO和社交媒体友好的应用程序。

Let’s go over the basic usage for React Helmet.

让我们来看一下React Helmet的基本用法。

安装和基本用法 (Installation & Basic Usage)

First, simply install the component into your project using npm or Yarn:

首先,只需使用npm或Yarn将组件安装到项目中:

$ npm i react-helmet

# or, using Yarn:
$ yarn add react-helmet

Now you can use the component in your app by adding the elements that should go in the head of the document as children to the Helmet component:

现在,您可以在应用程序中使用该组件,方法是将应将文档开头的元素作为子元素添加到Helmet组件中:

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

// ...

class App extends Component {
  render() {
    return (
      <div>
        <Helmet>
          <title>Turbo Todo</title>
          <meta name="description" content="Todos!" />
          <meta name="theme-color" content="#008f68" />
        </Helmet>
        {/* ... */}
      </div>
    );
  }
}

export default App;

With this, if you open your browser’s elements inspector you’ll see the title and meta elements in the head section. This won’t be reflected in the page’s source code however if you don’t have server-side rendering in place. In other words, without the use of React Helmet on the server, your pages won’t have the extra elements in the head for search engine and social media crawlers to see.

这样,如果打开浏览器的元素检查器,您将在头部看到标题和元元素。 但是,如果没有适当的服务器端渲染,这将不会反映在页面的源代码中。 换句话说,在服务器上不使用React Helmet的情况下,页面的头部将没有多余的元素供搜索引擎和社交媒体抓取工具查看。

覆盖值 (Overwriting values)

Components further down the tree can override values provided to the Helmet component on a higher level. For example, if our app has a ChildComponent like this:

树后面的组件可以覆盖更高级别提供给“ 头盔”组件的值。 例如,如果我们的应用程序具有这样的ChildComponent :

ChildComponent.js
ChildComponent.js
import React from 'react';
import { Helmet } from 'react-helmet';

export default () => {
  return (
    <div>
      <Helmet>
        <title>Extreme Todoz</title>
      </Helmet>
      <h1>Child Component!</h1>
    </div>
  )
}
import React, { Component } from 'react';
import { Helmet } from 'react-helmet';

import ChildComponent from './ChildComponent';

class App extends Component {
  render() {
    return (
      <div>
        <Helmet>
          <title>Turbo Todo</title>
          <meta name="description" content="Todos!" />
          <meta name="theme-color" content="#008f68" />
        </Helmet>
        <ChildComponent />
      </div>
    );
  }
}

export default App;

The resulting document title will be: Extreme Todoz, but the meta description and theme-color will still be in place because they are not overwritten.

最终的文档标题将为: Extreme Todoz ,但元描述和主题颜色仍将保留,因为它们不会被覆盖。

html和body的属性 (Attributes for html & body)

You can even include the html and body elements if you need to specify attributes for them. Here’s an example where we add a dark class name to the body element:

如果需要为它们指定属性,甚至可以包括html和body元素。 这是一个向body元素添加深色类名称的示例:

class App extends Component {
  render() {
    return (
      <div>
        <Helmet>
          <title>Turbo Todo</title>
          <meta name="description" content="Todos!" />
          <meta name="theme-color" content="#008f68" />
          <body class="dark" />
        </Helmet>
        {/* ... */}
      </div>
    );
  }
}

在服务器上渲染 (Rendering on the Server)

As we discussed, the full benefit of React Helmet becomes apparent when the app is rendered on the server so that the app gets served with the correct elements in the head of the document.

正如我们所讨论的,当应用程序在服务器上呈现时,React Helmet的全部好处变得显而易见,从而使应用程序在文档的开头具有正确的元素。

Assuming that you have a basic React server-side rendered app setup in place, you can call Helmet’s renderStatic method right after calling ReactDOMServer’s renderToString or renderToStaticMarkup to get an instance with properties for the Helmet data:

假设您已具备基本的React服务器端渲染应用程序设置,则可以在调用ReactDOMServer的renderToString或renderToStaticMarkup之后立即获取Helmet的renderStatic方法,以获取具有Helmet数据属性的实例:

index.js (server)
index.js(服务器)
import React from 'react';
import { renderToString } from 'react-dom/server';
import express from 'express';
import App from './src/App';
const app = express();
// ...

app.get('/*', (req, res) => {
  const app = renderToString(<App />);
  const helmet = Helmet.renderStatic();

  res.send(formatHTML(app, helmet));
});

app.listen(3000);

function formatHTML(appStr, helmet) {
  return `
    <!DOCTYPE html>
    <html lang="en">
      <head>
        ${helmet.title.toString()}
        ${helmet.meta.toString()}
      </head>
      <body>
        <div id="root">
          ${ appStr }
        </div>
        <script src="./bundle.js"></script>
      </body>
    </html>
  `
}

As you can see from this example, calling Helmet’s renderStatic returns an instance with properties like title and meta. You also have access to a bunch of other properties like link, script, noscript, style, htmlAttributes and bodyAttributes.

从该示例可以看到,调用Helmet的renderStatic返回一个具有title和meta之类的属性的实例。 您还可以访问许多其他属性,例如link , script , noscript , style , htmlAttributes和bodyAttributes 。

使用react-helmet-async进行异步渲染 (Async Rendering with react-helmet-async)

As brought up here by @mxstbr from Spectrum, React Helmet works synchronously which can potentially lead to issues on the server, especially with streaming. A fork of React Helmet comes to the rescue: react-helmet-async.

正如Spectrum 的@mxstbr在这里提到的那样React Helmet同步工作,这可能会导致服务器出现问题,尤其是流媒体。 React Helmet的一个分支可以解决: react-helmet-async

The API is the same, with the exception that a HelmetProvider needs to wrap the component tree on both the client and the server:

该API是相同的,除了HelmetProvider需要在客户端和服务器上包装组件树:

import React, { Component } from 'react';
import Helmet, { HelmetProvider } from 'react-helmet-async';

// ...

class App extends Component {
  render() {
    return (
      <HelmetProvider>
        <Helmet>
          <title>Turbo Todo</title>
          <meta name="description" content="Todos!" />
          <meta name="theme-color" content="#008f68" />
        </Helmet>
        {/* ... */}
      </HelmetProvider>
    );
  }
}

export default App;

🤕 And that’s it, React Helmet really makes it that easy! Here’s a great reference of everything that can go into a document’s head by @joshbuchea.

就是这样,React Helmet真的很容易! 这是@joshbuchea可以进入文档标题的所有内容的出色参考

翻译自: https://www.digitalocean.com/community/tutorials/react-react-helmet

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值