【发布时间】:2021-07-24 21:33:28
【问题描述】:
我有这个组件正在尝试渲染图表:
export default function Chart({ inputCurrency, outputCurrency, period }: ChartProps) {
....
const ref = useRef()
useEffect(() => {
const chart = createChart(ref.current, { width: 400, height: 300 })
}, [candleData])
return <div ref={ref} />
}
但是,我收到一条错误消息,提示 ref 的类型为 undefined:
Argument of type 'undefined' is not assignable to parameter of type 'string | HTMLElement'. TS2345
30 |
31 | useEffect(() => {
> 32 | const chart = createChart(ref.current, { width: 400, height: 300 })
| ^
33 | const candlestickSeries = chart.addCandlestickSeries()
34 | candlestickSeries.setData(candleData)
35 | }, [])
也尝试过CertainPerformance的建议:
export default function Chart({ inputCurrency, outputCurrency, period }: ChartProps) {
....
const ref = useRef<HTMLElement | undefined>()
useEffect(() => {
const chart = createChart(ref.current!, { width: 400, height: 300 })
}, [candleData])
return <div ref={ref} />
}
但是得到了这个错误:
Type 'MutableRefObject<HTMLElement | undefined>' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
Type 'MutableRefObject<HTMLElement | undefined>' is not assignable to type 'RefObject<HTMLDivElement>'.
Types of property 'current' are incompatible.
Type 'HTMLElement | undefined' is not assignable to type 'HTMLDivElement | null'.
Type 'undefined' is not assignable to type 'HTMLDivElement | null'. TS2322
104 | }, [candleData])
105 |
> 106 | return <div ref={ref} id="chart" />
| ^
107 | }
108 |
【问题讨论】:
-
试试
const ref = useRef<HTMLElement>(null) -
获取
Type 'null' is not assignable to type 'string | HTMLElement'. TS2345@PatrickRoberts
标签: reactjs typescript react-hooks ref