ref.current 总是未定义?

ref.current is always undefined?

我需要使用功能组件,所以不能直接使用useRef。这是我的代码:


import React,{forwardRef,useImperativeHandle,useRef,useEffect} from "react";
import "./style.css";

export default function App() {


  const ref_ = useRef();

useEffect(()=>{
    console.log(ref_)

})
  console.log(ref_)

  return (
    <div>
         <Demo/>
    </div>
  );
}

const Demo = forwardRef((props,ref)=>{

useImperativeHandle(ref,()=>({
  toggle(){
    console.log(123);
  }
}))

  return(
    <div ref={ref}>1234</div>

  )
})

在线代码: https://stackblitz.com/edit/forwardref-z68drh?file=src/App.js

我想在父组件上触发子组件的功能...有人能帮我吗?

您需要将 ref 本身传递给 Demo 组件:

function App() {
  const ref = useRef();
  return <Demo ref={ref}/>;
}

那么你可以使用 ref.current.toggle() 因为 useImperativeHandle.

https://stackblitz.com/edit/forwardref-z68drh-epz2xf?file=src/App.js