我希望在React组件加载后立即将焦点放在按钮上,以便用户可以只使用键盘来按下按钮。
这是我正在尝试做的事情,但这似乎不起作用。
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>
);
}
}
我正在使用tabler-react组件
答案 0 :(得分:2)
将componentDidUpdate()更改为componentDidMount(),如下所示:
componentDidMount(){
this.logButton.current.focus();
}
以及您从tabler-react使用的Button组件和定义为 rootRef 的Button组件 ref 来检查其在Button组件中的引用属性。
因此更改ref:
<Button rootRef={this.logButton} color="primary">A Button</Button>
答案 1 :(得分:0)
button
是HTML内置标记。您应该将Button
更改为button
(小写)componentDidUpdate
更改为componentDidMount
。