繁体   English   中英

在react组件中渲染整个html文件

[英]Render whole html file in react component

我正在通过API提供一些内容。 我想在我的React组件中显示来自API的响应。 响应是HTML,并通过webpack内联了所有资产。

我该怎么做?

我试了dangerouslySetInnerHTML但它使返回的html内的JavaScript崩溃了。

我的cmp:

import React, { Component } from 'react';
import axios from 'axios';

export default class Report extends Component {
constructor() {
    super();
    this.state = {
        id: null,
        report: null
    };
}

getParam(param){
    return new URLSearchParams(window.location.search).get(param);
}

componentWillMount() {
    axios.post(`/url`,
        {
            'id': this.getParam('id'),
        }
    )
        .then(res => {
            this.setState({id: res.data});
            setTimeout(() => {
                axios.get(`https://rg.ovh/`+this.state.id)
                    .then(res => {
                        this.setState({report: res.data})
                    });
            }, 1900);
        });
}

render() {
    return (
        <div dangerouslySetInnerHTML={ {__html: this.state.report} } />
    );
}

}

import axios from 'axios';
import React, { Component } from 'react';
import renderHTML from 'react-render-html';

class App extends Component {
  constructor() {
    super();
    this.state = {
      htmlString: ''
    };
  }

  componentDidMount() {
    axios.get('http://localhost:5000').then(response => {
      this.setState({ htmlString: response.data })
    }).catch(err => {
      console.warn(err);
    });
  }

  render() {
    const { htmlString } = this.state;

    return (
      <div className="App">
        {renderHTML(htmlString)}
      </div>
    );
  }
}

export default App;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM