簡體   English   中英

有條件地渲染內部的組件<Draggable> ,使用 react-draggable,正在破壞可拖動功能。 有任何想法嗎?

[英]Conditionally rendering a component inside of <Draggable>, using react-draggable, is breaking the draggable functionality. Any ideas?

我正在嘗試有條件地在另一個使用 react-draggable 的組件中渲染一個組件。 如果我的返回函數返回一個 div,則拖動可以正常工作。 如果我的函數返回 SomeComponent,則拖動會完全中斷。 我已經嘗試過 React.forwardRef 並將 ref 附加到 Draggable 上的 nodeRef 以及組件內的 ref 上,但這不起作用。 這可能是反應可拖動的限制嗎?

const Master = () => {
  const nodeRef = useRef(null);

  const renderComponent = (type) => {
    switch (type) {
      case "typography":
        // If we return <Typography />, drag stops working.
        // return <Typography content="Hello!" ref={nodeRef} />; // Not Working
        return <div ref={nodeRef}>hello</div>; // Working
      case "button":
        return <button>Click Me</button>;
      default:
        break;
    }
  };
  return (
    <Draggable nodeRef={nodeRef}>{renderComponent("typography")}</Draggable>
  );
};
const Typography = React.forwardRef(({ content }, ref) => {
  return <div ref={ref}>{content}</div>;
});

如果您想查看它,這里是一個分叉代碼框的鏈接。 https://codesandbox.io/s/gallant-voice-ly8jyj?file=/src/Master.js:113-673

感謝大家!

renderComponent調用包裝在div中似乎可以解決問題:

const Master = () => {
  const nodeRef = useRef(null);

  const renderComponent = (type) => {
    switch (type) {
      case "typography":
        return <Typography content="Hello!" />;
      case "button":
        return <button>Click Me</button>;
      default:
        break;
    }
  };
  return (
    <Draggable nodeRef={nodeRef}>
      <div ref={nodeRef}>{renderComponent("typography")}</div>
    </Draggable>
  );
};

在這種情況下,您也不需要forwardRef

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM