1.什么是useRef Hook?
useRef
就是createRef
的Hook版本用来获取元素, 只不过比createRef更强大一点
createRef只能获取普通元素和类元素,并且只能获取到类组件的实例对象,不能拿到函数式组件
import React, {createRef, useRef} from 'react'; class Home extends React.PureComponent{ render() { return ( <div>Home</div> ) } } function About() { return ( <div>About</div> ) } function App() { const pRef = createRef(); const homeRef = createRef(); function btnClick() { console.log(pRef.current); console.log(homeRef.current); } return ( <div> <p ref={pRef}>我是段落</p> <Home ref={homeRef}/> <About/> <button onClick={()=>{btnClick()}}>获取</button> </div> ) } export default App;
import React, {createRef, useRef} from 'react'; class Home extends React.PureComponent{ render() { return ( <div>Home</div> ) } } function About() { return ( <div>About</div> ) } function App() { // const pRef = createRef(); // const homeRef = createRef(); const pRef = useRef(); const homeRef = useRef(); function btnClick() { console.log(pRef.current); console.log(homeRef.current); } return ( <div> <p ref={pRef}>我是段落</p> <Home ref={homeRef}/> <About/> <button onClick={()=>{btnClick()}}>获取</button> </div> ) } export default App;
两种方法都能拿到ref,结果如下:
网络异常,图片无法展示
|
createRef.png
createRef和useRef
- useState和useRef区别:
useRef中保存的数据, 除非手动修改, 否则永远都不会发生变化
const age = useRef(18);
如果说useRef
也可以保存数据的话那么为什么还要有useState
呢?
function App() { const pRef = createRef(); const homeRef = useRef(); function btnClick() { console.log(pRef); // {current: p} console.log(homeRef); // {current: Home} } const [numState, setNumState] = useState(0); // const age = useRef(18); // {current: 18} const age = useRef(numState); // {current: 0} useEffect(()=>{ age.current = numState; }, [numState]); return ( <div> <p>上一次的值: {age.current}</p> <p>当前的值 :{numState}</p> <button onClick={()=>{setNumState(numState + 1)}}>增加</button> </div> ) } export default App;
总结一下:
useRef
可以获取元素,可以保存数据
和createRef
的区别是可以保存数据
和useState
的区别是:useRef
中保存的数据, 除非手动修改, 否则永远都不会发生变化