How to set focus to a materialUI TextField?

左心房为你撑大大i 提交于 2019-12-17 19:57:43

问题


How can I set the focus on a material-ui TextField component?

componentDidMount() {
    ReactDom.findDomNode(this.refs.myControl).focus()
}

I have tried above code, but it does not work :(


回答1:


You can use the autoFocus attribute.

<TextField value="some value" autoFocus />



回答2:


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:

function AutoFocusTextField(props) {
  const inputRef = React.useRef();

  React.useEffect(() => {
    const timeout = setTimeout(() => {
      inputRef.current.focus();
    }, 100);

    return () => {
      clearTimeout(timeout);
    };
  }, []);

  return <TextField inputRef={inputRef} {...props} />;
}

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




回答3:


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 && input.focus()}
/>

Material-ui doc says:

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




回答4:


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();
};

EDIT: 2 years later this still gathers downvotes... people, it was a "hello world" small project in react and typescript so... being completely noob in react, I tried to find a solution to this problem, found this question, the first answer didn't work for me, but with the help of other answers, here on SO, I managed to produce the code above, which works! So please, take 10 seconds and tell me why you're downvoting my answer.



来源:https://stackoverflow.com/questions/37949394/how-to-set-focus-to-a-materialui-textfield

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!