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 :(
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();
};
来源:https://stackoverflow.com/questions/37949394/how-to-set-focus-to-a-materialui-textfield