使用React头盔管理您的头脑

news/2024/7/5 0:52:55

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


http://www.niftyadmin.cn/n/3648314.html

相关文章

创业+社区点评:信息会过载吗?

看了创业社区之后第一句话就是“若邻的细分市场啊”。 “目前可能需要的是拥有下列资源的人”这个功能很实用&#xff0c;是若邻所没有的。对要关注的人提问的快速方式也很贴心。但是。。。现在用户少且精&#xff0c;容易组织起来。如果人数多了起来&#xff0c;不知道以现有的…

debian10 安装_如何在Debian 10上安装Jitsi Meet

debian10 安装The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program. 作者选择了“ 开放互联网/言论自由基金会”作为“ Write for DOnations”计划的一部分来接受捐赠。 介绍 (Introduction) Jitsi Me…

自然语言处理能够把全网内容组织到什么程度?

自然语言处理能够把全网内容组织到什么程度&#xff1f; Zhengyun 发表于创业社区 2007-03-27 23:23:40我的要求是不需要任何推动力&#xff0c;用户不需要做任何输入或搜索&#xff0c;社区内就已经围绕着细粒度的话题展开了。结果我们做到的自然语言处理后的主题收敛性很强&a…

resize_看看Resize Observer JavaScript API

resizeResize Observer is a new JavaScript API that’s very similar to other observer APIs like the Intersection Observer API. It allows for elements to be notified when their size changes. Resize Observer是一个新JavaScript API&#xff0c;与诸如Intersection…

新闻聚合引擎能把新闻组织到什么程度? 兼谈百度google新闻

zhengyun_ustc 2007-3-31书接上回《自然语言处理能够把全网内容组织到什么程度&#xff1f;》。百度新闻和google新闻都是不错的新闻聚合&#xff0c;内容组织得不错。那么我们的机会又在哪里呢&#xff1f;我们怎么才能提供一个新闻事件脉络呢&#xff1f;后面我会讲到百度和g…

javascript控制台_看一下JavaScript控制台API

javascript控制台The JavaScript console is an invaluable tool to help develop and debug our apps. With the console object and its logging methods, long are the days of of calling alert() to debug and get a variable’s value. On top of that, thanks to a work…

技术英雄会【一】:问周鸿祎一个问题

zhengyun_ustc 20070406下午创业英雄论坛&#xff0c;周鸿祎是被问问题最多的&#xff0c;也是最能讲的。周董也延续了以往的直言不讳。其中有一些说法和他以前的公开文字差不多&#xff0c;比如“创业心态&#xff1a;考虑失败比考虑成功多”&#xff0c;比如“成功者的创业初…

react前端ui的使用_使用React Morph变形UI过渡

react前端ui的使用Love them or hate them, animations in modern web design are probably here to stay. Unlike the glory days of jQuery, React out of the box does not provide any mechanism to perform such animations. Sure you could do a small bit of CSS wizard…