react的hooks的用法詳解
hooks的作用
它改變了原始的React類的開發(fā)方式,改用了函數形式;它改變了復雜的狀態(tài)操作形式,讓程序員用起來更輕松;它改變了一個狀態(tài)組件的復用性,讓組件的復用性大大增加。
useState
// 聲明狀態(tài)
const [ count , setCount ] = useState(0);
// 使用狀態(tài)
<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(()=>{
監(jiān)聽事件 window.addEventListener(“resize”,onResize)
return 移除監(jiān)聽()=>window.removeEventListener(“resize”,onResize)
},[])
返回 return size
使用 const size = useWinSize()
到此這篇關于react的hooks的用法詳解的文章就介紹到這了,更多相關react hooks用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決React報錯Encountered?two?children?with?the?same?key
這篇文章主要為大家介紹了React報錯Encountered?two?children?with?the?same?key解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
React?antd中setFieldsValu的簡便使用示例代碼
form.setFieldsValue是antd?Form組件中的一個方法,用于動態(tài)設置表單字段的值,它接受一個對象作為參數,對象的鍵是表單字段的名稱,值是要設置的字段值,這篇文章主要介紹了React?antd中setFieldsValu的簡便使用,需要的朋友可以參考下2023-08-08
react-json-editor-ajrm解析錯誤與解決方案
由于歷史原因,項目中 JSON 編輯器使用的是 react-json-editor-ajrm,近期遇到一個嚴重的展示錯誤,傳入編輯器的數據與展示的不一致,這是產品和用戶不可接受的,本文給大家介紹了react-json-editor-ajrm解析錯誤與解決方案,需要的朋友可以參考下2024-06-06

