如何在React中编程地使按钮获得焦点?

4

自动对焦对我不起作用,因为我需要(button2)在按钮1被单击时集中注意力,而不是在元素加载时。 这是我的代码:

const MyComponent = props =>{

    return(<div>
                <button id='button1'>Button1</button>
                <button id='button2'>Button2</button>
           </div>);
}

我尝试使用一个 ref,但是它似乎对按钮无效,只适用于文本框之类的元素;当我将 button2 替换为一个 <input> 时,它可以正常工作:

const MyComponent = props =>{
    const btnRef = useRef()
    const handleClick = ()=>{
        btnRef.current.focus()
    }
    return(<div>
                <button id='button1' onClick={handleClick}>Button1</button>
                <button id='button2'>Button2</button>
           </div>);
}

有方法可以让这个ref引用生效吗?或者有其他任何使按钮在程序中获得焦点的方法吗?
1个回答

2

你已经走在正确的道路上了,你还需要将引用附加到你想调用 .focus 的DOM元素上。

例如:

const MyComponent = () => {
  const btnRef = useRef();

  const handleClick = () => {
    btnRef.current.focus();
  };

  return (
    <div>
      <button id="button1" onClick={handleClick}>
        Button1
      </button>
      <button ref={btnRef} id="button2">
        Button2
      </button>
    </div>
  );
};

问题似乎是即使按钮具有浏览器焦点,也没有视觉指示。你可以提供这个功能。
使用styled-components的示例:
const Button = styled.button`
  &:focus {
    outline: 2px solid red;
  }
`;

const MyComponent = () => {
  const btnRef = useRef();

  const handleClick = () => {
    btnRef.current.focus();
  };

  return (
    <div>
      <button id="button1" onClick={handleClick}>
        Button1
      </button>
      <Button ref={btnRef} id="button2">
        Button2
      </Button>
    </div>
  );
};

Edit how-to-programmatically-focus-a-button-in-react

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接