- 用來獲取 DOM 元素,或者 class 組件實(shí)例 葡兑。
- 創(chuàng)建
useRef
時(shí)候,會創(chuàng)建一個原始對象赞草,只要函數(shù)組件不被銷毀讹堤,原始對象就會一直存在,那么我們可以利用這個特性房资,來通過useRef
保存一些數(shù)據(jù)蜕劝。
import React, {useRef} from "react";
import './App.css';
function App() {
const inputRef = useRef<any>(null);
const getVal = () =>{
console.log(inputRef.current.value);
}
return (
<div className="App">
<br />
<br />
<input type="text" ref={inputRef}/>
<br />
<br />
<button onClick={getVal}> 打印輸入的值 </button>
</div>
);
}
export default App;