为何 export default function index({ref }) { // 这里有提示报错:绑定元素“ref”隐式具有“any”类型。ts(7031)?

作者站长头像
站长
· 阅读数 14

我定义了一个组件如下:code-blockcontainer

import React, { useRef } from 'react'



export default function index({ref }) {  // 这里有提示报错:绑定元素“ref”隐式具有“any”类型。ts(7031)

  const clickButton = () => {
    console.log('输出子组件的实例信息:',  ref.current)
  }
  
  return (
    <div>
      <button onClick={clickButton} >点击按钮</button>
    </div>
  )
}

使用的时候:

import React, { useRef } from 'react';

import './App.css';

import CodeBlockContainer from './component/code-blockcontainer'

function App() {

  const childRef = useRef<HTMLDivElement>(null)

  return (
    <div className="App">
      <CodeBlockContainer ref={childRef}></CodeBlockContainer>
    </div>
  );
}

export default App;

===

问题是:定义组件时候这一行有报错:

export default function index({ref }) {  // 这里有提示报错:绑定元素“ref”隐式具有“any”类型。ts(7031)

请问这里应该如何进行处理呢?我变为:

{ref: React.RefObject<HTMLDivElement>} 

也会报错。

回复
1个回答
avatar
test
2024-08-11

需要使用使用 forwardRef 其次ref是第二个参数 不是第一个参数对象中

export const Example: FC = forwardRef((props, ref) => {
  return <div></div>
})
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容