【问题标题】:In ReactJS, how can I assign multiple ref to a single DOM?在 ReactJS 中,如何将多个 ref 分配给单个 DOM?
【发布时间】:2022-11-18 18:05:55
【问题描述】:

我有一个对话组件,我在其中创建了一个 ref,但我也想将 ref 从父级传递给它。我怎样才能做到这一点?

import { forwardRef } from "react";

export const PopOver = ({
  show = false,
  ...
}, ref) => {

  const thisRef = useRef(null);

  // dealing with UI changes with 'thisRef'

  return (
    <div
      ref={thisRef}, // How can I add a `ref` here?
      ....
    >
      Hello world
    </div>
  );
};

export default forwardRef(PopOver);

【问题讨论】:

    标签: reactjs react-ref


    【解决方案1】:

    您可以用另一个元素包装它并将父引用传递给它 像这样:

       <div ref={ref}>
        <div
          ref={thisRef}
          ....
        >
          Hello world
        </div>
      </div>
    

    或者如果你想替换 ref 你可以在 useEffect 中完成 像这样 :

    useEffect(()=>{
     if(ref.current){
      thisRef.current = ref.current
       }
    },[ref])
    

    【讨论】:

      【解决方案2】:

      不能将多个引用直接分配给同一个元素。但可以使用useEffect 将值赋值给另一个 ref

      const otherRef = useRef(null);
      const thisRef = useRef(null);
      
      useEffect(() => {
        otherRef.current = thisRef.current;
      }, [thisRef.current]);
      
      return <div ref={thisRef} />;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-27
        • 2022-11-14
        • 2012-01-07
        • 1970-01-01
        • 2016-09-23
        相关资源
        最近更新 更多