反应钩。设置状态值后,如何显示输入并获得输入焦点?

时间:2020-06-17 02:21:15

标签: reactjs react-hooks

如何在setstate值之后显示输入并获得输入焦点

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

export default function App() {
  const [state, setState] = useState(false);
  const refEl = useRef(null);
  const clickBtn = () => {
    setState(true);
    refEl.current.focus();
  };
  return (
    <div className="App">
      <button onClick={clickBtn}>showIbout</button>
      {state && <input ref={refEl} />}
    </div>
  );
}

1 个答案:

答案 0 :(得分:0)

您可以使用useEffect()

const { useState, useEffect, useRef } = React;


function App() {
  const [state, setState] = useState(false);
  const refEl = useRef(null);
  const clickBtn = () => {
    setState(true);
  };
  useEffect(()=>{
    if(state){
      refEl.current.focus();
    }
  },[state]);
  return (
    <div className="App">
      <button onClick={clickBtn}>showIbout</button>
      {state && <input ref={refEl} />}
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" />