【问题标题】:how to create a react-chart.js gradient line in typescript如何在打字稿中创建 react-chart.js 渐变线
【发布时间】:2022-01-03 04:30:10
【问题描述】:

我正在尝试使用 react-chartjs-2 和 typescript 创建渐变线

一切都很好,直到我尝试创建渐变线,这是打字稿抛出错误的地方,我很难摆脱。

这是组件代码:

import { useRecoilValue } from "recoil"
import { currencies, symbol } from "../../state/atoms"
import moment from 'moment';

import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import Actions from "../Actions";

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

const CurrencyGraph = () => {
  //getting graph numeric infos from the Recoil store
  const apiSymbol = useRecoilValue(symbol)
  const currencyInfos = useRecoilValue(currencies)

  // computing price array for the Y axis
  const prices = currencyInfos.map((item) => item[4])
  const priceLabel = prices.map(price => Number(price))

  // computing hours array for the X axis
  const time = currencyInfos.map((item) => item[6])
  let hours = time.map(time => moment.unix(Number(time)/1000).format("hh A"))
 
  // not displaying the grid by default
  ChartJS.defaults.scale.grid.display = false;

  const options = {
    responsive: true,
    scales: {
        y: {
            ticks: {
                // Include a dollar sign in the ticks
                callback: function(value:any, index:any, values:any) {
                    return '$' + value;
                }
            }
        }
    },
    plugins: {
      legend: {
        position: 'top' as const,
      },
      title: {
        display: true,
        text: apiSymbol,
      },
    },
  };

  //using canvas.getContext to create a gradient 
  const data = (canvas: { getContext: (arg0: string) => any; }) => {
    const ctx = canvas.getContext("2d");
    const gradient = ctx.createLinearGradient(0, 0, 0, 200);
    gradient.addColorStop(0, 'rgba(250,174,50,1)');   
    gradient.addColorStop(1, 'rgba(250,174,50,0)');

    const result = {
      labels: hours,
      datasets: [
        {
          label: 'currency value in $',
          data : priceLabel,
          tension:0.5,
          pointStyle: 'circle',
          pointRadius:1,
          pointBorderWidth:0,
          pointBorderColor:'black',
          borderWidth:2,
          backgroundColor: 'black',
          fill:true,
          borderColor: gradient,
          
        },
      ]
    }
    return result
  }

  return (
    <div className="graph">  
     <Line options={options} data={data} />
     <Actions />
    </div>
  )
}

export default CurrencyGraph

然后我无法编译,因为 typescript 抛出了这个错误:

TS2741: Property 'datasets' is missing in type '(canvas: { getContext: (arg0: string) => any; }) => { labels: string[]; datasets: { label: string; data: number[]; tension: number; pointStyle: string; pointRadius: number; pointBorderWidth: number; pointBorderColor: string; borderWidth: number; backgroundColor: string; fill: boolean; borderColor: any; }[]; }' but required in type 'ChartData<"line", (number | ScatterDataPoint | null)[], unknown>'.
    115 |   return (
    116 |     <div className="graph">  
  > 117 |      <Line options={options} data={data} />
        |                                   ^^^^^^
    118 |      <Actions />
    119 |     </div>
    120 |   )

我可能不太理解打字稿告诉我的内容。 我确实尝试像这样向数据添加类型:

type dataType = {
labels: [],
datasets: []
}

然后将类型添加到我的函数中,但它不能很好地工作,我得到了同样的错误

感谢任何可以提供帮助的人!

【问题讨论】:

    标签: typescript react-chartjs-2


    【解决方案1】:

    const data = (canvas: { getContext: (arg0: string) =&gt; any; }) 更改为

    const data = (canvas: HTMLCanvasElement) => {}
    

    然后在返回时做

    <Line options={options} data={data(canvasRef)} />
    

    您必须将canvas 元素的ref 传递给data 函数

    【讨论】:

    • 谢谢毗湿奴!我只是不确定如何使用 react hook useRef 在画布上放置参考?
    • 是的,使用useRef
    • @VishnuSajeev 你在哪里设置 useRef?我遇到了同样的问题
    • 你必须使用你的画布元素的引用。使用 useRef 将 ref 分配给 canvas 元素并使用它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 2019-10-22
    • 2021-06-15
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多