How to set focus to a materialUI TextField?

后端 未结 5 675
长发绾君心
长发绾君心 2020-12-11 00:09

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

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


        
相关标签:
5条回答
  • 2020-12-11 00:10

    AlienKevin is correct ( pass a ref callback to "TextField.inputProps" ), but you can also save the element reference on your "this" object, so that you can set focus later. Here is an example in Coffeescript:

    TextField
        inputProps:
            ref: (el)=>
                if el?
                    @input_element = el
    
    Button
        onClick:=> 
            @input_element.focus()
    
    0 讨论(0)
  • 2020-12-11 00:11

    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.

    0 讨论(0)
  • 2020-12-11 00:18

    You can use the autoFocus attribute.

    <TextField value="some value" autoFocus />
    
    0 讨论(0)
  • 2020-12-11 00:27

    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.

    0 讨论(0)
  • 2020-12-11 00:35

    For a material ui TextField you need to input the props for autoFocus in a inputProps object like this.

     <TextField inputProps={{ autoFocus: true }} />
    
    0 讨论(0)
提交回复
热议问题