如何在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>
);
}
答案 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" />