使用useEffect和useRef渲染重量图表,但会出错

时间:2020-06-16 23:23:04

标签: reactjs

轻型图表会创建自己的画布,而我无法将图形居中放置在页面中或将其移动到任何地方。我尝试不使用任何钩子。它呈现了图形,但不会响应我为其分配的任何CSS,因此我开始使用useRef,但仍然无法正常工作。我收到“ TypeError:t.appendChild不是函数”。我究竟做错了什么?

import React, { useEffect, useState, useRef } from 'react';
import { createChart } from 'lightweight-charts';
import axios from 'axios';
import './Chart.css';

const Chart = ({stock}) => {

    const [chartData, setChartData] = useState([]);
    const chartRef = useRef();


    useEffect(() => {

            const chart = createChart(chartRef, { width: 500, height: 400 });
            const lineSeries = chart.addLineSeries();
            lineSeries.setData(stockChartDatas);
            chart.timeScale().fitContent();
    },[])


    return (
            <div className="chart-container">
            <h2>Interactive 5 Years Historical Daily Chart</h2>
            <div ref={chartRef} />
            </div>
        )
    }
export default Chart;

1 个答案:

答案 0 :(得分:0)

您只需要使用chartRef.current

const chart = createChart(chartRef.current, { width: 500, height: 400 });

检查一下 https://codesandbox.io/s/hopeful-wright-wkn5q?file=/src/App.js