当锚标记出现在字符串响应中时,ReactJs 不会将锚标记呈现为 link

ReactJs not rendering anchor tag as a link when anchor tag comes inside the string response

我不熟悉 React js 并将我们的代码从 Freemarker 转移到 React 我得到一个包含锚标记的 Json 字符串响应,当我在浏览器上的 React js 中呈现此字符串时,它会将锚标记显示为纯文本而不是 link.

回复:

{
    "type": "paragraph",
    "paragraph": {
        "body": " <p> <a href=\"http://stg-testing.com/new-cars/jaguar\" target=\"_blank\">Jaguar</a> <a href=\"http://stg-testing.com/new-cars/landrover\" target=\"_blank\">Land Rover</a> has officially taken the covers off the fifth generation Range Rover SUV which now comes with a new look, new engine options and loaded with new technology with features galore. </p>"
    }
}

ReactJS 代码:

<div className="StoryBodyContent" id={`story_$${storyData.id}`}>
   {storyData.listElement.map(element => 
     (
       <p>{element.paragraph.body.replace("<p>","").replace("</p>","")}</p>
     ))
    }
</div>

ReactJS 输出:

预期输出:

尝试设置 innerHTML 而不是将其呈现为字符串。

<p dangerouslySetInnerHTML={
  element.paragraph.body.replace("<p>","").replace("</p>","")
}></p>

阅读 documentation 了解更多详情。

更好的实施方式是获取您传递给 a 标签的数据并将其作为附加属性传输到您的 JSON 数据,而不是传递 包含数据的整个锚标记。

重构代码:

JSON 数据:

{
    "type": "paragraph",
    "paragraph": {
        "body": {
           "firstLink" : "http://stg-testing.com/new-cars/jaguar",
           "secondLink" : "http://stg-testing.com/new-cars/landrover",
           "firstLinkText" : "Jaguar",
           "secondLinkText" : "Land Rover",
           "children" : has officially taken the covers off the fifth generation 
            Range Rover SUV which now comes with a new look, new engine options 
            and loaded with new technology with features galore"
         }
    }
}

REACT.JS

<div className="StoryBodyContent" id={`story_$${storyData.id}`}>
   {storyData.listElement.map(element => 
     (
       <p><a href={element.paragraph.body.firstLink}>
              {element.paragraph.body.firstLinkText}
           </a>
           <a href={element.paragraph.body.secondLink}>
              {element.paragraph.body.secondLinkText}
           </a>
           {children}
       </p>
     ))
    }
</div>