reactjs - React useRef 更改不会导致依赖于 ref.current 的组件重新渲染

标签 reactjs

此追加销售组件的目的是在特定区域(门户)呈现某些内容。因此它将接受一个 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/

相关文章:

reactjs - React 新手,购物车中的增量/减量

javascript - 根据当前路线突出显示选项卡

javascript - Material UI+React 悬停在选项卡上将无法正常打开和关闭

javascript - getPastEvents 未定义(重新)

javascript - 如何解决 Promise pending 的问题

javascript - 显示像 redux devTool 这样的 React reducer 操作

javascript - 在javascript中以编程方式填写和提交textarea

android - react native :-How to use a common drawer and toolbar across all pages with control

javascript - 返回变量时使用三元运算符而不是 if 语句

javascript - Reactjs 使用相似的按钮将不同的属性传递给相同的函数?