用 typescript 反应plotly js

Mey*_*ron 4 reactjs plotly

我将react-plotly.js与打字稿一起使用,并从中得到以下错误:

No overload matches this call.
  Overload 1 of 2, '(props: PlotParams | Readonly<PlotParams>): Plot', gave the following error.
    Type '({ type: string; mode: string; x: number[]; y: number[]; marker: { color: string; }; } | { type: string; x: number[]; y: number[]; mode?: undefined; marker?: undefined; })[]' is not assignable to type 'Data[]'.
      Type '{ type: string; mode: string; x: number[]; y: number[]; marker: { color: string; }; } | { type: string; x: number[]; y: number[]; mode?: undefined; marker?: undefined; }' is not assignable to type 'Data'.
        Type '{ type: string; mode: string; x: number[]; y: number[]; marker: { color: string; }; }' is not assignable to type 'Data'.
          Type '{ type: string; mode: string; x: number[]; y: number[]; marker: { color: string; }; }' is not assignable to type 'Partial<BoxPlotData>'.
            Types of property 'type' are incompatible.
              Type 'string' is not assignable to type '"box" | undefined'.
  Overload 2 of 2, '(props: PlotParams, context: any): Plot', gave the following error.
    Type '({ type: string; mode: string; x: number[]; y: number[]; marker: { color: string; }; } | { type: string; x: number[]; y: number[]; mode?: undefined; marker?: undefined; })[]' is not assignable to type 'Data[]'.  TS2769

    20 | };
    21 | 
  > 22 | const Dashboard = () => <div><Plot data={data} layout={layout} /></div>;
       |                                    ^
    23 | 
    24 | export default Dashboard;
    25 |
Run Code Online (Sandbox Code Playgroud)

我用它发送到以下数据,但它似乎不起作用。

const data = [{
    type: 'scatter',
    mode: 'lines+points',
    x: [1, 2, 3],
    y: [2, 6, 3],
    marker: { color: 'red' },
}, {
    type: 'bar',
    x: [1, 2, 3],
    y: [2, 5, 3],
}];

const layout = {
    width: 640,
    height: 480,
    title: 'A Fancy Plot',
};

const Dashboard = () => <div><Plot data={data} layout={layout} /></div>;
Run Code Online (Sandbox Code Playgroud)

这与我发送的数据有关吗?我安装了react-plotly 的类型,因此,我收到此错误。

小智 6

我在尝试将 React-plotly.js 与 TypeScript 一起使用时遇到了类似的问题。

在这里,您传递的“线+点”不是有效的类型,但即使您传递了正确的类型,仍然面临问题。

我就是这样解决的!

所需包:

npm i plotly.js react-plotly.js

开发依赖:

npm i --save-dev @types/plotly.js @types/react-plotly.js

Chart.tsx文件示例:

import React from "react";
import Plotly from "plotly.js";
import createPlotlyComponent from "react-plotly.js/factory";
const Plot = createPlotlyComponent(Plotly);

export default function LineChart() {
  const data = [
    {
      x: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      y: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      mode: "lines",
    },
  ];
  const layout = { title: "Chart Title" };

  return <Plot data={data} layout={layout} />;
}
Run Code Online (Sandbox Code Playgroud)