reactjs 在< h1>react中渲染时重置焦点

rxztt3cl  于 2023-03-29  发布在  React
关注(0)|答案(1)|浏览(110)

当一个新的页面标题呈现时,我想在该页面上重置焦点,这样点击<tab>将导致浏览器转到这个主页面标题之后的可聚焦/可制表元素。

qlfbtfca

qlfbtfca1#

const PageTitle = ({title}) => {
  const titleHeaderRef = useRef(null as null | HTMLHeadingElement);
  useEffect(() => {
    if (titleHeaderRef.current !== null) {
      // First, make the element focus-able.
      titleHeaderRef.current.setAttribute('tabIndex', '-1');

      // Reset focus to this primary header.
      titleHeaderRef.current.focus();
      titleHeaderRef.current.blur();

      // Finally, make the element non-focus-able.
      titleHeaderRef.current.removeAttribute('tabIndex');

      // To see this behavior in action, wrap this dom calls in a 5 second setTimeout, and tab around the page before this timeout is hit.
    }
  }, []);

  return (
    <Typography ref={titleHeaderRef}>
      {title}
    </Typography>
  );
};

相关问题