react的hooks的用法詳解
阿新 • • 發佈:2020-10-14
hooks的作用
它改變了原始的React類的開發方式,改用了函式形式;它改變了複雜的狀態操作形式,讓程式設計師用起來更輕鬆;它改變了一個狀態元件的複用性,讓元件的複用性大大增加。
useState
// 宣告狀態 const [ count,setCount ] = useState(0); // 使用狀態 <p>You clicked {count} times</p> <button onClick={()=>{setCount(count+1)}}>click me</button>
useEffect
一個引數
useEffect(()=>{ console.log("首次渲染與更新") })
模擬:
componentDidMount componentDidUpdate
一個引數帶return
useEffect(()=>{ console.log("首次渲染與更新") return ()=>{console.log(首次解除安裝)} })
模擬:
- componentDidMount
- componentDidUpdate
return
- componetWillUnmount
- componentDidUpdate
第二個引數是空陣列,return
useEffect(()=>{ console.log("首次渲染與更新") return ()=>{console.log(首次解除安裝)} },[])
相對於生命週期的componentDidMount和componetWillUnmount
第二個引數是具體的值
useEffect(()=>{ console.log("首次渲染與更新") return ()=>{console.log(首次解除安裝)} },[num])
模擬
- componentDidMount
- componentDidUpdate(update只對num有用)
return
- componetWillUnmount
- componentDidUpdate(update只對num有用)
useRef
const inp = useRef(null) <input ref={inp}> //呼叫 inp.current.value
自定義hook
定義:const [size,setSize] = useState({height:xxx,width:xxx})
處理:
const onResize = ()=>{setSize({width:xxx,height:xxx})} useEffect(()=>{ 監聽事件 window.addEventListener(“resize”,onResize) return 移除監聽()=>window.removeEventListener(“resize”,onResize) },[])
返回 return size
使用 const size = useWinSize()
到此這篇關於react的hooks的用法詳解的文章就介紹到這了,更多相關react hooks用法內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!