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和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中生存的数据, 除非手动修改, 否则永世都不会发生变革 |