此追加销售组件的目的是在特定区域(门户)呈现某些内容。因此它将接受一个 DOM 元素,并在其上创建 createPortal
。问题是 widgetDom 始终为 null 并导致 createPortal 没有机会渲染。
在消费者中,我使用 useRef
并将 widgetRef.current
传递给 Upsell 组件。我期望当 widgetRef
附加真实元素时,widgetRef.current
更改将导致 Upsell 组件重新渲染,但它没有发生。
你能看一下下面的代码或 sandbox ?谢谢!
const Upsell: React.FC<{ widgetDom: HTMLElement | null }> = ({ widgetDom }) => {
return (
<div className="box">
<h1>Order Summary</h1>
{widgetDom && createPortal(<h2>Order Summary Widget</h2>, widgetDom)}
</div>
);
};
export default function App() {
const widgetDom = React.useRef<HTMLElement | null>(null);
return (
<div className="App">
<div className="box" style={{ width: "60%" }}>
<div className="box">
<h1>Ad Selection</h1>
</div>
<Upsell widgetDom={widgetDom.current} />
</div>
<div className="box" style={{ width: "40%" }}>
<div id="orderSummaryWidget" ref={widgetDom} className="box"></div>
</div>
</div>
);
}
最佳答案
设计引用don't cause a re-render when they change :
Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.
最简单的解决方法是使用状态而不是引用:
export default function App() {
const [widgetDom, setWidgetDom] = useState<HTMLElement | null>(null);
return (
<div className="App">
<div className="box" style={{ width: "60%" }}>
<div className="box">
<h1>Ad Selection</h1>
</div>
<Upsell widgetDom={widgetDom} />
</div>
<div className="box" style={{ width: "40%" }}>
<div id="orderSummaryWidget" ref={setWidgetDom} className="box"></div>
</div>
</div>
);
}
关于reactjs - React useRef 更改不会导致依赖于 ref.current 的组件重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64706338/