反应组件渲染时如何将焦点设置在按钮上?

Shu*_*ora 3 reactjs

我想在反应组件加载后立即将焦点设置在按钮上,以便用户可以仅使用键盘按下按钮。

这就是我试图做的,但这似乎不起作用。

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.logButton = React.createRef();

  }

  componentDidUpdate(){
     this.logButton.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <Button ref={this.logButton}  outline color="primary" size="sm" onClick={this.logManualRequestModal}>
         Log request
        </Button>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用tabler-react组件

Jay*_*vel 5

将 componentDidUpdate() 更改为 componentDidMount() 如下所示:

componentDidMount(){
     this.logButton.current.focus();
  }
Run Code Online (Sandbox Code Playgroud)

并且您使用tabler-react中的 Button 组件和定义为rootRef 的Button 组件ref检查它们在 Button 组件中的 ref 属性。

所以像这样改变 ref :

<Button rootRef={this.logButton} color="primary">A Button</Button>
Run Code Online (Sandbox Code Playgroud)

演示参考