如何显示来自 json 响应的 "anchor tag" 文本?

How to display the text with "anchor tag", coming from json response in react?

我有以下代码:

JSON 响应:

{
   "url": ["http://google.com"],
   "text": ["Click <a>me</a> for help"]
}

代码:

import React, { Fragment } from 'react';

export const Print = (props) => (
  <Fragment>
    {(props.text[0].split('/n').length && props.text[0].split('/n').map(i => {
      return <p dangerouslySetInnerHTML={{ __html: i }}></p>
    })) || text[0]}
  </Fragment>
)

我的要求:

<p> Click <a href="http://google.com">me</a> for help <p>

这应该像上面那样工作。我无法理解如何呈现 json,因此 dangerouslySetInnerHTML 将从“url”中获取锚标记作为响应并将其分配给 i 在代码中。

代码将在不同的文件中。该文件将从不同的文件调用,并且 JSON 响应将作为 prop.

发送到该文件

此答案仅适用于您的具体情况。它忽略了几个 <a> 标签并且只适用于干净的 <a> 标签,而不是 <a class="whatever">。还有,注意dangerouslySetInnerHTML,是easy to inadvertently expose your users to a cross-site scripting

const response = {
  "url": ["http://google.com", "http://example.com"],
  "text": ["Click <a>me</a> for help", "And <a>me</a> for test"]
};

export default function App() {
  const els = response.text.map((text, i) => text.replace("<a>", `<a href=${response.url[i]}>`));

  return (
    <>
      {els.map((el, i) => <p key={i} dangerouslySetInnerHTML={{ __html: el }} />)}
    </>
  );
}

Playground