我有以下代码,无法编译:
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
初始值,或者我该如何使它生效?
答案 0 :(得分:1)
您可以考虑观察ref的变化,直到它不为空为止。
useEffect(() => {
//Check for cvRef.current != null
}, [cvRef] );