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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/166053.html
標籤:python
