如何将焦点设置到 antd Input.Password 组件?

edj*_*jia 4 reactjs antd

我正在尝试将焦点集中在一个input.password领域。是否可以?

我没有看到 antd 文档的任何信息。我想知道是否可能

Input(Input.TextArea)通过 ref有一个Input(textAreaRef)属性。但在 中Input.Password,我找不到任何有关此的信息。有办法完成我的问题吗?

Dan*_*ore 6

密码输入与其他文本输入没有什么不同。首先,您必须创建对输入的引用,然后您可以focus()随时调用其方法来聚焦输入。下面的代码在组件安装时聚焦输入:

import React from "react";
import ReactDOM from "react-dom";
import { Icon, Input } from "antd";
import "antd/dist/antd.css";
import "./index.css";

class LoginForm extends React.Component {
  passwordInput = null;

  componentDidMount() {
    this.passwordInput.focus();
  }

  render() {
    return (
      <div className="App">
        <Input
          prefix={<Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />}
          type="password"
          placeholder="Password"
          ref={input => {
            this.passwordInput = input;
          }}
        />
      </div>
    );
  }
}

ReactDOM.render(<LoginForm />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)

在这里尝试一下


skv*_*991 5

有时您使用 ref 指向 Component 而不是 DOM 元素,因此,请尝试以下操作:

对于来自 antd 库的输入组件:

import React, { useRef, useEffect } from "react";
import { Input, Form } from "antd";
import "antd/dist/antd.css";

const MyComponent = () => {
  // Same as React.createRef()
  const passwordInput = useRef(null);

  useEffect(() => {
    if (passwordInput.current) {
      // or, if Input component in your ref, then use input property like:
      // passwordInput.current.input.focus();
      passwordInput.current.focus();
    }
  }, [passwordInput]);

  return (
    <Form>
      <Form.Item name="login">
        <Input type="text" placeholder="Login" />
      </Form.Item>
      <Form.Item name="password">
        <Input type="password" placeholder="Password" ref={passwordInput} />
      </Form.Item>
    </Form>
  );
};

export default MyComponent;
Run Code Online (Sandbox Code Playgroud)

如果是 DOM 元素

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

const MyComponent2 = () => {
  const passwordInput = useRef(null);

  useEffect(() => {
    if (passwordInput.current) {
      passwordInput.current.focus();
    }
  }, [passwordInput]);

  return (
    <form>
      <input type="text" placeholder="Login" />
      <input type="password" placeholder="Password" ref={passwordInput} />
    </form>
  );
};

export default MyComponent2;
Run Code Online (Sandbox Code Playgroud)

这是codesandbox上的示例

PS useEffect hook 的工作原理与 Class 组件中的 componentDidMount 几乎相同