例如,我有一个使用React.js
构建的在线商店应用程序,我想使用HTML元标记自定义在社交媒体上共享的URL的外观(例如,添加说明和图片)。此外,我希望特定产品(例如https://www.mywebsite.com/product/<productId>
)的路线预览appropriate图片及其说明,因此仅在index.html
中包含meta标签是不可接受的。
我尝试使用react-helmet
和其他用于添加元标记的软件包,但它们没有帮助。我猜是因为react-helmet
在应用程序渲染后而不是仅在URL共享时添加了元标记。
是使用服务器端渲染解决此问题的唯一方法,还是只有从前端处理它的方法?
按照下面的示例逐步进行相同的操作
步骤1 –使用NPM安装以下命令
npm install react-meta-tags --save
注意:您也可以使用React Helmet (a third party library)]实现此目的>
第2步–在类Component中使用MetaTag Component
import React from 'react'; import MetaTags from 'react-meta-tags'; class Component1 extends React.Component { render() { return ( <div className="wrapper"> <MetaTags> <title>Your Page 1</title> <meta name="description" content="Your description here.." /> <meta property="og:title" content="Your App" /> <meta property="og:image" content="Your path/to/image.jpg" /> </MetaTags> <div className="content"> Your Content here... </div> </div> ) } }
注意:在标签上定义id,因此,如果您导航到其他页面,则较旧的meta标签将被新的meta标签替换/更新。
第3步-ReactTitle组件:
如果只想在页面上添加标题,则可以使用ReactTitle。
import React from 'react'; import {ReactTitle} from 'react-meta-tags'; class Component2 extends React.Component { render() { return ( <div className="wrapper"> <ReactTitle title="Your Page 2"/> <div className="content"> Your Page 2 Content </div> </div> ) } }
服务器使用示例:
import MetaTagsServer from 'react-meta-tags/server'; import {MetaTagsContext} from 'react-meta-tags'; /* Import other required modules */ /* some serve specific code */ app.use((req, res) => { //make sure you get a new metatags instance for each request const metaTagsInstance = MetaTagsServer(); //react router match match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { let reactString; try{ reactString = ReactDomServer.renderToString( <Provider store={store}> {/*** If you are using redux ***/} {/* You have to pass extract method through MetaTagsContext so it can catch meta tags */} <MetaTagsContext extract = {metaTagsInstance.extract}> <RouterContext {...renderProps}/> </MetaTagsContext> </Provider> ); } catch(e){ res.status(500).send(e.stack); return; } //get all title and metatags as string const meta = metaTagsInstance.renderToString(); //append metatag string to your layout const htmlStr = (` <!doctype html> <html lang="en-us"> <head> <meta charSet="utf-8"/> ${meta} </head> <body> <div id="content"> ${reactString} </div> </body> </html> `); res.status(200).send(layout); }); });
根据上述代码,我们必须对服务器渲染选项进行以下操作
JSX布局:
您可能还使用React来定义布局,在这种情况下,您可以使用metaTagsInstance中的getTags方法。上面的服务器端示例的布局部分将如下所示。
//get all title and metatags as React elements
const metaTags = metaTagsInstance.getTags();
//append metatag string to your layout
const layout = (
<html lang="en-us">
<head>
<meta charSet="utf-8"/>
{metaTags}
</head>
<body>
<div id="app" dangerouslySetInnerHTML={{__html: reactString}} />
</body>
</html>
);
const htmlStr = ReactDomServer.renderToString(layout);
res.status(200).send(htmlStr);