简体   繁体   English

尝试在 JSX 中呈现字符串中的链接

[英]Trying to render a link within a string, within JSX

I'm trying to render a link, which is found in an array of objects with properties and values.我正在尝试呈现一个链接,该链接位于具有属性和值的对象数组中。

const arr = [
  {
    id: 1,
    title: "This is a title",
    body: [
      "This is some stuff. Lorem ipsum, lorizzle for shizzle.",
      "Click here to send an <Link to="mailto:yo@mail.com">email</Link>"
    ]
  },
  {
    id: 2,
    title: "This is another title",
    body: [
      "Moar stuff.",
      "Here is ma' <Link to="mailto:hello@mail.com">email</Link>"
    ]
  }
]

I'm using this logic to map through the array's objects and store them inside an array of components.我通过数组的对象使用这个逻辑到 map 并将它们存储在一个组件数组中。 This works as intended, if all I'm intending to do is just render some text in a paragraph.如果我只想在段落中呈现一些文本,这将按预期工作。 When it comes to links, simply this won't work.当涉及到链接时,这根本行不通。 My guess is that React takes the string for text, and renders the entire thing as text.我的猜测是 React 将字符串作为文本,并将整个内容呈现为文本。 It doesn't care of the contents.它不关心内容。

            <section key={item.key} className="">
                <h2 className="text-base">{item.title}</h2>
                {
                    item.body.map(function(paragraph) {
                        return(
                            <p className="text-sm">{paragraph}</p>
                        )
                    })
                }
            </section>

I've tried enclosing the Link tags within curly braces, to concatenate the string and email (as it would appear in the HTML), string template literals.我尝试将 Link 标签括在花括号中,以连接字符串和 email(如 HTML 中所示),字符串模板文字。 Nothing worked.没有任何效果。

I'm not sure there is a dependency I'm missing or a step.我不确定是否缺少我缺少的依赖项或步骤。 Perhaps the approach I'm taking is wrong?也许我采取的方法是错误的? Maybe what I'm trying to do is impossible in React?也许我想要做的事情在 React 中是不可能的?

Would appreciate some light shed on this matter.希望能对此事有所了解。

Some corrections in your question what i found你的问题中的一些更正我发现了什么

Assuming you wanted to have a anchor tag假设你想要一个锚标签

so tweaking your array, Changes所以调整你的数组,改变

  1. <a href='mailto:yo@mail.com'>email</a> instead of <Link to="mailto:yo@mail.com">email</Link> <a href='mailto:yo@mail.com'>email</a>而不是<Link to="mailto:yo@mail.com">email</Link>
  2. "Click here to send an <Link to="mailto:yo@mail.com">email</Link>" instead "Click here to send an <a href='mailto:yo@mail.com'>email</a>" , quotes should be used properly inside double quotes you need to have single quotes or vice versa "Click here to send an <Link to="mailto:yo@mail.com">email</Link>"而不是"Click here to send an <a href='mailto:yo@mail.com'>email</a>" /Link> "Click here to send an <a href='mailto:yo@mail.com'>email</a>" ,引号应该在双引号内正确使用,你需要有单引号,反之亦然

Doing the above changes adding the solution进行上述更改添加解决方案

Here you can have multiple approaches在这里你可以有多种方法

  1. Using a library使用库

Example例子
html-react-parser html-react-解析器

Code Snippet代码片段

App.js应用程序.js

import React, { Fragment } from "react";
import Parser from "html-react-parser";

const arr = [
  {
    id: 1,
    title: "This is a title",
    body: [
      "This is some stuff. Lorem ipsum, lorizzle for shizzle.",
      "Click here to send an <a href='mailto:yo@mail.com'>email</a>"
    ]
  },
  {
    id: 2,
    title: "This is another title",
    body: [
      "Moar stuff.",
      "Here is ma' <a href='mailto:hello@mail.com'>email</a>"
    ]
  }
];
export default function App() {
  return (
    <Fragment>
      {arr.map(item => (
        <section key={item.key} className="">
          <h2 className="text-base">{item.title}</h2>
          {item.body.map(function(paragraph) {
            return <p className="text-sm">{Parser(paragraph)}</p>;
          })}
        </section>
      ))}
    </Fragment>
  );
}
  1. Use the dangerouslySetInnerHtml , but this method has some flaws as mentioned in the docs使用dangerouslySetInnerHtml ,但这种方法有一些缺陷,如文档中所述

dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM. dangerouslySetInnerHTML 是 React 在浏览器 DOM 中使用 innerHTML 的替代品。 In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack.通常,从代码中设置 HTML 是有风险的,因为很容易无意中将您的用户暴露给跨站点脚本 (XSS) 攻击。

Code snippet代码片段

App.js应用程序.js

import React, { Fragment } from "react";

const arr = [
  {
    id: 1,
    title: "This is a title",
    body: [
      "This is some stuff. Lorem ipsum, lorizzle for shizzle.",
      "Click here to send an <a href='mailto:yo@mail.com'>email</a>"
    ]
  },
  {
    id: 2,
    title: "This is another title",
    body: [
      "Moar stuff.",
      "Here is ma' <a href='mailto:hello@mail.com'>email</a>"
    ]
  }
];
export default function App() {
  return (
    <Fragment>
      {arr.map(item => (
        <section key={item.key} className="">
          <h2 className="text-base">{item.title}</h2>
          {item.body.map(function(paragraph) {
            return (
              <p
                className="text-sm"
                dangerouslySetInnerHTML={{ __html: paragraph }}
              />
            );
          })}
        </section>
      ))}
    </Fragment>
  );
}

In the above approach, you can do a dompurify and set with dangerouslysetinnerhtml to avoid the XSS attacks在上面的方法中,你可以做一个dompurify并设置为 dangerouslysetinnerhtml 来避免 XSS 攻击

import DOMPurify from "dompurify";

<p
  className="text-sm"
  dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(paragraph) }}
/>;

I hope this will give a better understanding我希望这会给你一个更好的理解

you might try using dangerouslySetInnerHtml .您可以尝试使用dangerouslySetInnerHtml

Something like this: <div dangerouslySetInnerHtml={paragraph} />像这样的东西: <div dangerouslySetInnerHtml={paragraph} />

This attribute is named like that with a reason, so be careful about what you send in there, as it might lead to XSS injections.这个属性的命名是有原因的,所以要小心你在那里发送的内容,因为它可能会导致 XSS 注入。

Learn more about it here: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml在此处了解更多信息: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

This would be a very naive approach to transfering jsx within array.这将是在数组中传输 jsx 的一种非常幼稚的方法。

const arr = [
  {
    id: 1,
    title: "This is a title",
    body: [
      ["This is some stuff. Lorem ipsum, lorizzle for shizzle."],
      ["Click here to send an ", <Link to="mailto:yo@mail.com">email</Link>"]
    ]
  },
item.body.map(function(paragraph) {
    const content = paragraph.reduce((combined, elem) => {
        return content + elem;
    });

    return(
        <p className="text-sm">{paragraph}</p>
    )
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM