为子组件设置 ref 时,类型 ReactElement 上不存在属性“ref”

问题描述 投票:0回答:0

当我尝试使用子函数设置 ref 时,出现类似这样的错误 ReactElement 类型上不存在属性“ref”,有没有办法解决这个问题?

const childRef = useRef()
 
const child = Children.only(children)

  const setRef = (el: React.Ref<HTMLDivElement>) => {
    childRef.current = el

    const { ref } = child // error here 
    if (ref) {
      ref.current = el
    }
  }

  return (
    <>
      {cloneElement(child, {
        ref: setRef,
        onClick: () => handleClick(),
        onMouseEnter: () => showTooltip(),
        onMouseLeave: () => hideTooltip(),
      })}
  ...
reactjs typescript
© www.soinside.com 2019 - 2024. All rights reserved.