问题
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