如何在 reactjs 中呈现 html 字符串

How to render html string in reactjs

当我从 Shopify 的 API 中提取数据时,我在获取 HTML 时遇到了问题。我可以访问 Shopify API,但它没有以正确的方式呈现信息。当我访问它时会发生什么,是我得到带有标签的 HTML,而不是标签为我做格式化。看起来像这样。

网站上显示的信息

<p class="p1"><strong>Coolin' for the season.</strong></p> <p class="p1">- True to size fit</p> <p class="p1">- Made with a Champion© 50% cotton/50% polyester hoodie.</p> <p class="p1">- Embroidered front Safe House and "Champion C logo" decoration on the cuff.</p> <p class="p1">- Wash in cold water to prevent shrinkage</p> <p class="p1"><strong>Brought to you exclusively by Safe House Chicago.</strong></p> <p class="p2"> </p> <p class="p1"><strong>*Please allow 14-21 days for delivery for your icey item.*</strong></p> <p class="p2"> </p> <p class="p1"><strong>Model is wearing a size medium</strong></p>

而不是我需要的

我希望如何呈现信息

Coolin' for the season.

- True to size fit

- Made with a Champion© 50% cotton/50% polyester hoodie.

- Embroidered front Safe House and "Champion C logo" decoration on the cuff.

- Wash in cold water to prevent shrinkage

Brought to you exclusively by Safe House Chicago.



*Please allow 14-21 days for delivery for your icey item.*



Model is wearing a size medium

这是我的代码的样子(我稍后会分开)

ShopProduct.js

import React, { Component } from 'react';
import PageHeader from './PageHeader'
import { fetchSingleProduct, fetchAllProducts } from "../utils/shopifyHelpers"
import styles from '../styles';


export default class ShopProduct extends Component {
  constructor(props){
    super(props);
    this.state = {
      image: '',
      title: '',
      productInfo: ''
    }
  }
  singleProduct(){
    let productDetails
    fetchSingleProduct('7078139269')
    .then((product) => {
      this.setState({
        productInfo: product.description
      })
    })
  }
  componentDidMount(){
    this.singleProduct()
  }


  render() {
    return (
      <div>
        <PageHeader header="Placeholder"/>
        <div className="row">
          <div className="col-sm-6">
            <h1 className="text-center">{this.state.title}</h1>
          </div>
          <div className="col-sm-6">
            <h1 className="text-center">{this.state.productInfo}</h1>
          </div>
        </div>
      </div>
    )
  }
}

我需要做什么才能在没有所有标签的情况下正确呈现信息?

要在 HTML 中呈现此字符串,您需要使用 dangerouslySetInnerHTML 属性,试试这个:

<div dangerouslySetInnerHTML={{__html: a}}></div>

此处 a 将包含您在问题中粘贴的字符串。

检查 jsfiddle 工作示例:https://jsfiddle.net/dd1ckue2/