简体   繁体   中英

Access ref from class component in functional component with React

I have a class component in React with a ref and I want to access it within a functional component inside of it. I tried passing the ref as a prop, but then it says that it's undefined. So then I tried accessing it with this.refs but it's undefined too.

function GetOffset() {
  const [offset, setOffset] = useState(0);
  useEffect(() => {
    function handleScroll() {
      
    console.log(this.refs);
      
  }, [offset]);
}

I want to use getBoundingClientRect() to check an offset of an element but first I need to access the ref from inside this component.

I read that using a class component would work, but I need the useEffect() hook. Any tips?

useRef

const MyFunctionalComponent = () => {
   const ref = useRef();
   const [offset, setOffset] = useState(0);
   useEffect(() => {
      // access ref.current
   },[offset]);
   
   return <MyClassComponent ref={ref}/>
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM