【问题标题】:How to render a plotly object in React JSX?如何在 React JSX 中渲染一个 plotly 对象?
【发布时间】:2022-12-14 09:00:57
【问题描述】:

我正在尝试绘制一个整数数组,以响应来自 asp.net 后端的站点前端。具体来说,它来自控制器。我可以使用这个整数数组创建一个热图对象。如果可能的话,我想在 JSX 中渲染这个对象。我无法将它映射到 html,因为它只是一个对象。

目前我正在 renderHeatMap 函数中创建 plotly 热图。该站点可以呈现该图,但会抛出以下错误:“未捕获的错误:对象作为 React 子对象无效(已找到:[object Promise])。如果您打算呈现子对象的集合,请改用数组。”

我在网站的 App.js 部分可能会尝试什么?

import React, { Component } from 'react';
import Plotly from './plotly.js';

export default class App extends Component {
    static displayName = App.name;

    constructor(props) {
        super(props);
        this.state = { binaryData: [], loading: true };
    }

    componentDidMount() {
        this.populateWeatherData();
    }

    static renderHeatMap(binaryData)
    {
        var heatMap = [
            {
                z: [binaryData.slice(0, 7658134), binaryData.slice(7658135,15316269)],
                type: 'heatmap'
            }
        ];

        let heatMapObj = Plotly.newPlot('heatMapSection', heatMap);

        return <div> {heatMapObj}</div>
    }

    render() {
        let contents = this.state.loading
            ? <p><em>Loading... Please refresh once the ASP.NET backend has started. See <a href="https://aka.ms/jspsintegrationreact">https://aka.ms/jspsintegrationreact</a> for more details.</em></p>
            : App.renderHeatMap(this.state.binaryData);

        return (
            <div>
                <h1 id="tabelLabel" >Weather forecast</h1>
                <p>This component demonstrates fetching data from the server.</p>
                {contents}
            </div>
        );
    }

    async populateWeatherData() {
        const response = await fetch('weatherforecast');
        const data = await response.json();
        this.setState({ binaryData: data, loading: false });
    }
}

【问题讨论】:

    标签: reactjs jsx render


    【解决方案1】:

    我想出了解决这个问题的方法。您可以将 plotly 对象作为 html 对象返回。这是一个最佳解决方案,因为没有违反 App.js 和 index.js 之间的关系,因为 App.js 将只返回一个 html 对象而不尝试呈现对象。这是我使用的存储库的链接https://github.com/plotly/react-plotly.js/。下面我包含了这个存储库中的一个示例,说明如何将 plotly 对象作为 HTML 返回。

    import React from 'react';
    import Plot from 'react-plotly.js';
    
    class App extends React.Component {
      render() {
        return (
          <Plot
            data={[
              {
                x: [1, 2, 3],
                y: [2, 6, 3],
                type: 'scatter',
                mode: 'lines+markers',
                marker: {color: 'red'},
              },
              {type: 'bar', x: [1, 2, 3], y: [2, 5, 3]},
            ]}
            layout={{width: 320, height: 240, title: 'A Fancy Plot'}}
          />
        );
      }
    }

    【讨论】:

      猜你喜欢
      • 2020-06-28
      • 2019-08-01
      • 1970-01-01
      • 2021-01-07
      • 2022-12-11
      • 2016-10-29
      • 1970-01-01
      • 2018-07-19
      • 2019-03-19
      相关资源
      最近更新 更多