如何将Material UI Textfield集中在按钮单击上?

vuv*_*uvu 8 reactjs 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>
Run Code Online (Sandbox Code Playgroud)

roo*_*h84 12

您需要使用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>

    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我使用的是 @material-ui 1.12.3,需要在 `TextField` 属性中使用 `inputRef` 而不是 `ref` (3认同)

44k*_*rma 9

如果您使用的是无状态功能组件,那么您可以使用 React 钩子。

import React, { useState, useRef } from "react";

let MyFunctional = (props) => {

  let textInput = useRef(null);

  return (
    <div>
      <Button
        onClick={() => {
          setTimeout(() => {
            textInput.current.focus();
          }, 100);
        }}
      >
        Focus TextField
      </Button>
      <TextField
        fullWidth
        required
        inputRef={textInput}
        name="firstName"
        type="text"
        placeholder="Enter Your First Name"
        label="First Name"
      />
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)