通过渲染道具分配useRef

时间:2020-04-15 20:49:07

标签: reactjs

使用Render props模式,我想看看是否有一种方法可以使用当前设置进行这项工作。我有一个Parent组件,它使用Example组件作为包装器来在其中渲染一些子代。我想将Example内部的ref传递给渲染道具中的一个子对象。这可能吗 ?

const Example = ({ children }) => {
  const ref = useRef(null);
  const [open, SetOpen] = useState(false);
  const [controls] = useCustomAnimation(open, ref);

  return (
    <div>
      {children({ ref })}
    </div>
  );
};

const Parent = () => {
  return (
    <div>
      <Example>
        {ref => {
          <motion.div
            ref={ref}
          >
           {console.log('ref= ', ref)}
          ....... more children
          </motion.div>;
        }}
       </Example>
    </div>
  );
};

1 个答案:

答案 0 :(得分:0)

是的,您当前的文件几乎完全正确。我设置了example,但要点如下:

const Example = ({ children }) => {
  const ref = useRef(null);
  return <div>{children({ ref })}</div>;
};

const Parent = () => {
  return (
    <div>
      <Example>
        {({ ref }) => {
          console.log(ref);
          return <input type="text" ref={ref} />;
        }}
      </Example>
    </div>
  );
};

注意:您需要解构要传递给children函数的对象。