import React,{useState} from 'react'
export default ()=>{
const [count,setCount]=useState(0);
return(
<div>
current count:{count}
<button onClick={(c)=>{setCount(count+1); console.log(count)}}>add</button>
</div>
)
}
如果οnclick={(count)=>{ setCount(count+1) } }
这时实现不了count的加一,在浏览器上只能加一次,并且显示【object object】1
因为这里的onclick react已经封装了,参数count是这个点击事件的回调
<button onClick={(c)=>{setCount(count+1); console.log(count)}}>add</button>
改成c 不与count重名就可以实现count加法
hooks封装一层,实现自定义hook
import React,{useState} from 'react'
function useCount(initvalue){
const [count,setCount]=useState(initvalue);
return [
count,
()=>{
setCount(count+1);
}
]
}
export default ()=>{
const [count,addcount]=useCount(0);
return(
<div>
current count:{count}
<button onClick={(c)=>{addcount()}}>add</button>
</div>
)
}
个人理解,自定义了useCount的hook钩子
其实就是useState的一层封装,让useState干活加一,然后return解构赋值,换一个名字
addcount是return的那个回调,onclick时调用,那个参数c可以省略
export default 的函数用useCount