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

时间:2019-06-05 03:32:23

标签: reactjs antd

我正在尝试将焦点放在input.password字段上。有可能吗?

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

Input(Input.TextArea)通过引用具有Input(textAreaRef)属性。但在Input.Password中,我对此一无所获。有办法解决我的问题吗?

3 个答案:

答案 0 :(得分:1)

您还可以将refs用于Input.password。

import React, { Component } from 'react'

export default class container extends Component {
  constructor(props) {
    super(props);

    this.password = React.createRef();
  }

  componentDidMount() {
    this.password.current.focus();
  }

  render() {
    return (
      <div>
        <input type="password" ref={this.password}/>
      </div>
    )
  }
}

引用提供了一种方法,可以访问在render方法中创建的DOM节点或React元素。

答案 1 :(得分:1)

密码输入与其他文本输入没有区别。首先,您必须创建对输入的引用,然后可以随时调用其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"));

Try it here

答案 2 :(得分:0)

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

对于来自antd库的Input组件:

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;

如果是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;

这是codesandbox

上的示例

P.S。 useEffect钩子与Class组件中的componentDidMount几乎相同