我正在嘗試有條件地在另一個使用 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
感謝大家!
uj5u.com熱心網友回復:
renderComponent
將呼叫包裝在 a 中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
在這種情況下你也不需要
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/484146.html