首页 > 解决方案 > 如何将 Material UI 文本字段集中在按钮单击上?

问题描述

单击按钮后如何聚焦文本字段。我尝试使用 autoFocus,但没有成功:示例沙箱

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

标签: reactjsmaterial-ui

解决方案


您需要使用 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>
       <br />
       <TextField
         label="My Textfield"
         id="mui-theme-provider-input"
         inputRef={this.textInput} 
       />
     </div>

    );
  }
}

将 Material-UI v3.6.1 的 ref 更新为 inputRef。


推荐阅读