实时字幕/Suspense/ref的妙用/MutationObserver

chrome 设置 搜索“实时字幕

Suspense的 Promise由并行改为了串行
https://sorrycc.com/react-19-rc-suspense/
解法:
提前准备好数据,在 Render 时仅需要消费那个 Promise

export const Route = createFileRoute('/')({
  loader: ({ context: { queryClient } }) => {
    queryClient.ensureQueryData(repoOptions('tanstack/query'))
    queryClient.ensureQueryData(repoOptions('tanstack/table'))
  },
  component: () => (
    <Suspense fallback={<p>...</p>}>
      <RepoData name="tanstack/query" />
      <RepoData name="tanstack/table" />
    </Suspense>
  ),
})

ref的妙用

https://github1s.com/timolins/react-hot-toast/blob/main/src/components/toaster.tsx#L15-L45
const ToastWrapper = ({
  id,
  className,
  style,
  onHeightUpdate,
  children,
}: ToastWrapperProps) => {
  const ref = React.useCallback(
    (el: HTMLElement | null) => {
      if (el) {
        const updateHeight = () => {
          const height = el.getBoundingClientRect().height;
          onHeightUpdate(id, height);
        };
        updateHeight();
        new MutationObserver(updateHeight).observe(el, {
          subtree: true,
          childList: true,
          characterData: true,
        });
      }
    },
    [id, onHeightUpdate]
  );

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

MutationObserver
目标节点及其整个子树(subtree: true):任何后代节点的变化也会被捕捉。
子节点的添加或删除(childList: true):如果有新的子节点被添加到目标节点或有子节点被移除,观察者会捕捉到。
字符数据的变化(characterData: true):如果目标节点或其子节点的文本内容发生变化,观察者也会捕捉到。

posted @ 2024-06-21 17:03  被咯苏州  阅读(2)  评论(0编辑  收藏  举报