在 <h1> 渲染时重置焦点

问题描述 投票:0回答:1

当一个新的页面标题呈现时,我想重置该页面上的焦点,这样点击

<tab>
将导致浏览器转到可聚焦/可标记元素after这个主页面标题。

reactjs accessibility focus onfocus autofocus
1个回答
0
投票
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>
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.