How to set focus to a materialUI TextField?

白昼怎懂夜的黑 提交于 2019-11-28 11:59:17
Antonis Zisis

You can use the autoFocus attribute.

<TextField value="some value" autoFocus />

autoFocus was also not working for me, perhaps since this is a component that's not mounted when the top-level component loads. I had to do something a lot more convoluted to get it to work:

const focusUsernameInputField = input => {
  if (input) {
    setTimeout(() => {input.focus()}, 100);
  }
};

return (
  <TextField
    hintText="Username"
    floatingLabelText="Username"
    ref={focusUsernameInputField}
  />
);

Note that for some reason it does not work without the setTimeout. For more info see https://github.com/callemall/material-ui/issues/1594.

For React 16.8.6, you should use the inputRef property of TextField to set focus. I tried ref property but it doesn't work.

<TextField
  inputRef={input => input.focus()}
/>

Material-ui doc says:

inputRef: Use this property to pass a ref callback to the native input component.

I stumbled across this questions looking for solution to the same problem. I found about autoFocus but found that it only works when the page first loads, not after form submit. The way I finally found it can be done is by adding a ref to the child TextField and the calling select() on the form submit:

<form onSubmit={this.onSubmit}>
            <TextField ref="amountComp" ... />
</form>

and

onSubmit(event: any): void {
    // save form
    (this.refs["amountComp"] as TextField).select();
};
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!