Ref 在 useEffect 中属于 undefined 类型

时间:2021-05-02 02:46:45

标签: reactjs typescript react-hooks ref

我有一个试图渲染图表的组件:

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 |

1 个答案:

答案 0 :(得分:0)

在创建 ref 时,您需要向 TypeScript 指出 ref 的类型为 HTMLElement(或未定义):

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} />
}