PBa*_*Jen 12 reactjs react-helmet
我创建了一个服务器端React应用,它将返回html,如下所示:
const html = renderToString(<App />);
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<title>A Cool Page</title>
<link rel="stylesheet" href="${ROOT}/static/index.css">
</head>
<body>
<div id="root">${html}</div>
<script src="${ROOT}/client-bundle.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我读到很多人一直在使用反应头盔来管理头部中的内容。我想知道何时可以直接包含上述内容,使用它有什么好处。
Saj*_*kar 19
react-helmet允许设置将由搜索引擎和社交媒体爬虫读取的元标记。这使得服务器端渲染和 React Helmet 成为创建对 SEO 和社交媒体友好的应用程序的动态组合。
例如:
import { Helmet } from 'react-helmet';
<Helmet>
<title>Turbo Todo</title>
<meta name="description" content="test on react-helmet" />
<meta name="theme-color" content="#ccc" />
</Helmet>
Run Code Online (Sandbox Code Playgroud)
Lex*_*son 17
一个主要的好处或react-helmet是当您在树中有多个带有<head>标签的组件,并且<meta>标签具有相同的属性/值时。
例如,如果在索引页面组件上具有:
const html = renderToString(<App />);
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="description" content="This is the index page description">
<title>A Cool Index Page</title>
</head>
</html>
Run Code Online (Sandbox Code Playgroud)
但是在叶子页面组件上,您还有一个<head>包含元标记的标记:
<html>
<head>
<meta name="description" name="This is the unique leaf page description">
<title>A Cool Leaf Page</title>
<link rel="stylesheet" href="${ROOT}/static/index.css">
</head>
</html>
Run Code Online (Sandbox Code Playgroud)
注意,在我们的两个页面组件之间name="description",树中有两个具有相同属性值的meta标签。您可能会认为这可能导致重复,但是react-helmet可以解决此问题。
如果某人最终停留在叶子页面上,则react-helmet会覆盖索引/站点级别的描述元标记,并呈现较低级别的一个,即专门用于叶子页面的标记。
它也将包含视口元标记,因为它不必被覆盖。
由于react-helmet在叶子页面上<head>出现,因此将显示如下:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="description" name="This is the unique leaf page description">
<title>A Cool Leaf Page</title>
<link rel="stylesheet" href="${ROOT}/static/index.css">
</head>
</html>
Run Code Online (Sandbox Code Playgroud)
这两种方法都应该有效。但是对于 react-helmet,头部也被视为一个组件,并且更像 react。此外,虽然这很不寻常,但您可以将一些 props 或 state 与元数据绑定以实现动态头部。一种情况是在不同语言之间切换。
| 归档时间: |
|
| 查看次数: |
10719 次 |
| 最近记录: |