如何将 Material UI Textfield 聚焦在按钮单击上?

IT技术 reactjs material-ui
2021-04-16 06:02:53

单击按钮后如何聚焦文本字段。我尝试使用 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>
4个回答

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

这不会将边框宽度设置为文本字段的焦点宽度。当您专注于输入时,边框宽度从 1px 增加到 2px,但执行此方法会导致边框宽度保持在 1px。
2021-06-01 06:02:53
我在@material-ui 1.12.3 上,需要使用inputRef而不是refTextField道具中
2021-06-11 06:02:53

如果您使用的是无状态功能组件,那么您可以使用 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>
  );
};

首先,onclick必须像 一样正确onClick
然后如果你想在你的JSX代码中使用它,它会有所帮助。
我用 react 16 测试了它,它有效。

 <button onClick={() => this.myTextField.focus()}>
    Click to focus Textfield
 </button>

<TextField
       label="My Textfield"
       id="mui-theme-provider-input"
       inputRef={(el) => (this.myTextField = el)} />

如果您将 Material-ui<TextField/>与 react 功能组件一起使用,则可以focus使用inputRef. 这里的技巧是 if 条件if(input != null)你可以简单地做:

<TextField
    variant="filled"
    inputRef={(input) => {
      if(input != null) {
         input.focus();
      }
    }}
/>

这是一个适合您的工作示例。CodeSandBox- Material-ui-TextFieldFocus