类型'HTMLCanvasElement |的参数不能将'null'分配给类型的参数

时间:2020-10-31 21:27:19

标签: reactjs typescript react-typescript

我有以下代码,无法编译:

import React, {useEffect} from 'react'
import {Card, Image} from 'semantic-ui-react'
import * as chart from 'chart.js'



export const PieChartCard = () => {

    const cvRef = React.useRef<HTMLCanvasElement>(null);

    useEffect(() => {

        const c = new chart.Chart(cvRef.current, {

        })
    });

    return (
        <Card>
            <canvas ref={cvRef} width="400" height="400"></canvas>
            <Card.Content>
                <Card.Header>Matthew</Card.Header>
                <Card.Meta>
                    <span className='date'>Joined in 2015</span>
                </Card.Meta>
                <Card.Description>
                    Matthew is a musician living in Nashville.
                </Card.Description>
            </Card.Content>
        </Card>
    )

}

编译器抱怨

Argument of type 'HTMLCanvasElement | null' is not assignable to parameter of type 'string | HTMLCanvasElement | CanvasRenderingContext2D | ArrayLike<HTMLCanvasElement | CanvasRenderingContext2D>'.
  Type 'null' is not assignable to type 'string | HTMLCanvasElement | CanvasRenderingContext2D | ArrayLike<HTMLCanvasElement | CanvasRenderingContext2D>'.  TS2345

    11 |     useEffect(() => {
    12 | 
  > 13 |         const c = new chart.Chart(cvRef.current, {
       |                                   ^
    14 | 
    15 |         })
    16 |     });

我正在尝试在React中使用ChartJS。如何避免null初始值,或者我该如何使它生效?

1 个答案:

答案 0 :(得分:1)

您可以考虑观察ref的变化,直到它不为空为止。

useEffect(() => {
   //Check for cvRef.current != null
}, [cvRef] );