从HackerNewsApi后端接收的HTML标记和特殊字符,未在视图中解码



我正在从hackerNews API检索JSON数据。我收到了存储在后端的评论,如下所示:

by: "metakermit"
id: 19665566
kids: [19665689]
parent: 19664663
text: "A 15% cost reduction – not bad.<p>Possibly interesting – I&#x27;m working on developing a similar battery - solar panel off-the-shelf system that would be suited for people who live in cities (e.g. if you want to put a solar panel on your balcony):<p><a href="https:&#x2F;&#x2F;www.craftstrom.com&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.craftstrom.com&#x2F;</a>"
time: 1555338679
type: "comment" . 

当我在浏览器视图中呈现上述数据时,特殊字符和 html 标记按 JSON 中显示。

有人可以帮忙吗?

你可以

使用 dangerouslySetInnerHTML 属性/指令来告诉 react 按原样解释 html。

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }
  createMarkup() {
    return {__html: '<h3> this is a header </h3> normal text'};
  }
  render() {
    return (
      <div>
        <div dangerouslySetInnerHTML={this.createMarkup()}></div>
      </div>
    );
  }
}

工作堆栈闪电战

参考:

反应文档

我使用了html-react-parser库,它对我有用。https://github.com/remarkablemark/html-react-parser#usage

非常感谢@Abdelkarim艾尔·阿梅尔。感谢您的回复。

最新更新