首页 文章

如何在按钮单击时关注材质UI文本字段?

提问于
浏览
1

单击按钮后如何聚焦文本字段 . 我试图使用autoFocus,但它没有成功:Example sandbox

<div>
    <button onclick={() => this.setState({ focus: true })}>
      Click to focus Textfield
    </button>
    
<TextField label="My Textfield" id="mui-theme-provider-input" autoFocus={this.state.focus} /> </div>

1 回答

  • 2

    你需要使用ref,参见https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element

    class CustomTextInput extends React.Component {
      constructor(props) {
        super(props);
        // create a ref to store the textInput DOM element
        this.textInput = React.createRef();
        this.focusTextInput = this.focusTextInput.bind(this);
      }
    
      focusTextInput() {
        // Explicitly focus the text input using the raw DOM API
        // Note: we're accessing "current" to get the DOM node
        this.textInput.current.focus();
      }
    
      render() {
        // tell React that we want to associate the <input> ref
        // with the `textInput` that we created in the constructor
        return (
            <div>
              <button onClick={this.focusTextInput}>
                Click to focus Textfield
              </button>
           
    <TextField label="My Textfield" id="mui-theme-provider-input" ref={this.textInput} /> </div> ); } }

相关问题