Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 如何添加元标记以共享React.js中的特定链接?_Html_Reactjs_React Router_Meta Tags_React Helmet - Fatal编程技术网

Html 如何添加元标记以共享React.js中的特定链接?

Html 如何添加元标记以共享React.js中的特定链接?,html,reactjs,react-router,meta-tags,react-helmet,Html,Reactjs,React Router,Meta Tags,React Helmet,比如说,我有一个使用React.js构建的在线商店应用程序,我想使用HTML元标记定制社交媒体上共享的URL的外观(例如添加描述和图像)。此外,我需要特定产品的路线(例如https://www.mywebsite.com/product/)预览合适的图片及其描述,因此不能只在index.html中包含meta标记 我曾尝试使用react头盔和其他用于添加元标记的包,但它们没有帮助。我猜,这是因为在应用程序呈现后添加了meta标记,而不仅仅是在某个地方共享URL时 使用服务器端渲染是解决此问题的唯

比如说,我有一个使用
React.js
构建的在线商店应用程序,我想使用HTML元标记定制社交媒体上共享的URL的外观(例如添加描述和图像)。此外,我需要特定产品的路线(例如
https://www.mywebsite.com/product/
)预览合适的图片及其描述,因此不能只在
index.html
中包含meta标记

我曾尝试使用
react头盔
和其他用于添加元标记的包,但它们没有帮助。我猜,这是因为
在应用程序呈现后添加了meta标记,而不仅仅是在某个地方共享URL时


使用服务器端渲染是解决此问题的唯一方法,还是有一种方法可以仅从前端处理此问题?

按照下面的示例一步一步地执行相同的操作

步骤1–使用NPM安装以下命令

npm install react-meta-tags --save
注意:您也可以使用

步骤2–在类组件中使用MetaTag组件

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>
      )
  }
}
从“React”导入React;
从“反应元标记”导入元标记;
类Component1扩展了React.Component{
render(){
返回(
你的第1页
你的内容在这里。。。
)
}
}
注意:在标签上定义id,这样,如果您导航到其他页面,旧的元标签将被新的元标签替换/更新

步骤3-标题组件:

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);
  });
});
如果您只想在页面上添加标题,可以改用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>
      )
  }
}
从“React”导入React;
从'react meta tags'导入{ReactTitle};
类Component2扩展了React.Component{
render(){
返回(
您的第2页内容
)
}
}
服务器使用示例:

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);
  });
});
从'react meta tags/server'导入metatags服务器;
从“react meta tags”导入{MetaTagsContext};
/*导入其他必需的模块*/
/*有些服务于特定的代码*/
应用程序使用((请求、回复)=>{
//确保每个请求都有一个新的metatags实例
常量metaTagsInstance=MetaTagsServer();
//反应路由器匹配
匹配({
路由,位置:req.url
},(错误,重定向位置,渲染器操作)=>{
让我们来讨论这个问题;
试一试{
reactString=ReactDomServer.renderToString(
{/***如果您使用的是redux***/}
{/*您必须通过MetaTagsContext传递extract方法,这样它才能捕获meta标记*/}
);
}
捕获(e){
res.status(500)、send(e.stack);
返回;
}
//获取所有标题和元标记作为字符串
const meta=metaTagsInstance.renderToString();
//将元标记字符串附加到布局中
常量htmlStr=(`
${meta}
${reactString}
`);
资源状态(200)。发送(布局);
});
});
根据上面的代码,我们必须为服务器渲染选项执行以下操作

  • 导入MetaTagsServer表单服务器
  • 导入MetaTagsContext表单服务器
  • 创建MetaTagsServer的新实例
  • 将组件包装在MetaTagsContext中,并将提取方法作为道具传递
  • 使用MetaTagsServer实例的renderToString提取元字符串
  • 将元字符串附加到html模板中
  • JSX布局:

    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);
      });
    });
    
    您也可以使用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);
    
    //获取所有标题和元标记作为React元素
    const metaTags=metaTagsInstance.getTags();
    //将元标记字符串附加到布局中
    常量布局=(
    {metaTags}
    );
    const htmlStr=ReactDomServer.renderToString(布局);
    资源状态(200).发送(htmlStr);
    
    这通常就是需要服务器端渲染(SSR)的原因。至少你可以使用它。话虽如此,这正是像或这样的库存在的原因。@AlexanderStaroselsky感谢您的回复。实际上,我一直在考虑创建一个API端点,该端点将使用EJS模板为特定产品呈现适当的元标记,只是想确保没有后端就无法处理这个问题?您需要首先加载HTMLDOM,在这里加载JS文件以实现react。我不是在批评,我也有同样的想法。我只是好奇