【问题标题】:Ref is of type undefined inside useEffectRef 在 useEffect 中是 undefined 类型
【发布时间】: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&lt;HTMLElement&gt;(null)
  • 获取Type 'null' is not assignable to type 'string | HTMLElement'. TS2345@PatrickRoberts

标签: reactjs typescript react-hooks ref


【解决方案1】:

您需要在创建 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} />
}

【讨论】:

  • 我刚试了一下,但出错了。用错误更新了我原来的帖子
猜你喜欢
  • 2021-03-29
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
  • 1970-01-01
  • 2021-06-04
相关资源
最近更新 更多