我创建了一个服务器端 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>
我读到很多人一直在使用 react-helmet
来管理 head 中的内容。我想知道使用它有什么好处,当我可以直接包含如上所示时。
最佳答案
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>
但是在叶子页面组件上,您还有一个<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>
请注意,我们的两个页面组件之间有两个具有相同属性值的元标记 name="description"
在我们的树上。您可能认为这可能会导致重复,但是 react-helmet
解决了这个问题。
如果有人最终到达叶子页面,react-helmet 会覆盖索引/站点级描述元标记并呈现较低级别的元标记,即专门用于叶子页面的元标记。
它还将包含视口(viewport)元标记,因为它不必被覆盖。
因为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>
关于reactjs - react Helm 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52690820/