如何在reactjs中呈现html字符串

时间:2017-02-07 05:07:25

标签: reactjs jsx

当我从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>
    )
  }
}

如果没有所有标签,我需要做些什么才能正确呈现信息?

1 个答案:

答案 0 :(得分:0)

要在HTML中呈现此字符串,您需要使用dangerouslySetInnerHTML属性,请尝试以下操作:

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

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

点击jsfiddle查看工作示例:https://jsfiddle.net/dd1ckue2/