如何在 React.js 中基于按钮单击来聚焦元素

Poo*_*oja 0 reactjs

我有两个按钮和两个文本框。当我单击按钮 1 时,它应该自动聚焦在文本框 1 上。当我单击按钮二时,它应该自动聚焦在文本框2上。

代码:

import React, { Component } from "react";
import "./styles.css";

class App extends Component {
  handleClick(){
    alert("hi");
  }
  render() {
    return (
      <div className="App">
        <div>
          <button onClick={this.handleClick}>One</button>
          <button onClick={this.handleClick}>Two</button>
        </div>
        <div>
          <input type="text" name="one" id="one" placeholder="one" /> 
        </div>
        <div>
          <input type="text" name="two" id="two" placeholder="two" /> 
        </div>
      </div>
    );
  }
}
export default App;
Run Code Online (Sandbox Code Playgroud)

链接到codesandbox

Deh*_*oos 6

焦点调用称为副作用。所以你必须直接访问 HTML dom 元素来调用它。

Refs ( https://reactjs.org/docs/refs-and-the-dom.html ) 是访问此原生元素的反应方式。您基本上设置了一个容器变量并将其分配给感兴趣的反应元素。在幕后,React 会将该变量链接到本机 dom 元素,您可以在该元素上调用原始焦点函数。

有两种不同的方法可以做到这一点,如下所示。

import React, { useRef } from "react";
import "./styles.css";

function FormFunctionalComponent() {
  const input1 = useRef(null);
  const input2 = useRef(null);

  const handleClick1 = () => {
    input1.current.focus();
  }; 

  const handleClick2 = () => {
    input2.current.focus();
  };
  return (
    <div className="App">
      <h1>Functional Component</h1>
      <button onClick={handleClick1}>One</button>
      <button onClick={handleClick2}>Two</button>
      <div>
        <input ref={input1} type="text" name="one" id="one" placeholder="one" />
      </div>
      <div>
        <input ref={input2}  type="text" name="two" id="two" placeholder="two" />
      </div>
    </div>
  );
}

class FormClassComponent extends React.Component {
  constructor(props) {
    super(props);
    this.input1 = React.createRef();
    this.input2 = React.createRef();
  }
  handleClick1 = () => {
    this.input1.current.focus();
  }; 

  handleClick2 = () => {
    this.input2.current.focus();
  };

  render() {
    return (
      <div className="App">
        <h1>Class Component</h1>
        <button onClick={this.handleClick1}>One</button>
        <button onClick={this.handleClick2}>Two</button>
        <div>
          <input ref={this.input1} type="text" name="one" id="one" placeholder="one" />
        </div>
        <div>
          <input ref={this.input2} type="text" name="two" id="two" placeholder="two" />
        </div>
      </div>
    );
  }
}

export default function App() {
  return (
    <>
      <FormFunctionalComponent /> <hr />
      <FormClassComponent />
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

这是工作的codesandbox 示例。

https://codesandbox.io/s/blissful-fog-xoj9t?file=/src/App.js