简体   繁体   English

使用 React 从功能组件中的 class 组件访问 ref

[英]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.我在 React 中有一个带有 ref 的 class 组件,我想在其中的功能组件中访问它。 I tried passing the ref as a prop, but then it says that it's undefined.我尝试将 ref 作为道具传递,但随后它说它未定义。 So then I tried accessing it with this.refs but it's undefined too.因此,我尝试使用this.refs访问它,但它也是未定义的。

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.我想使用getBoundingClientRect()来检查元素的偏移量,但首先我需要从该组件内部访问 ref。

I read that using a class component would work, but I need the useEffect() hook.我读到使用 class 组件可以工作,但我需要useEffect()挂钩。 Any tips?有小费吗?

useRef使用参考

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


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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