hook
react16.8的新特性,函数式组件也可以模拟使用state ,ref, 类似生命周期,等其他特性了
常用的hook
- State Hook useState
- Effect Hook useEffect
- Ref Hook useRef
useState
-
useState跟一个参数为state的初始值
-
左侧[state,setState],一个状态跟一个set状态方法,构成一对
function ReactCom(){ const [count, setCount] = React.useState('初始值'); function handelClick(){ setCount(count+1) } return ( <div onClick={handelClick}>函数式组件的state{count}</div> ) } ReactDOM.render(<ReactCom></ReactCom>,document.getElementById('reactId'))
useRef
function ReactCom(){
const refDom=React.useRef();
function handelClick(){
console.log(refDom)
}
return (
<div onClick={handelClick} ref={refDom}>useRef</div>
)
}
ReactDOM.render(<ReactCom></ReactCom>,document.getElementById('reactId'))
useEffect
useEffect用来模拟生命周期 compontDidMount + componentDidUpdate +componentWillUnmount
第一个参数
回调函数再返回一个函数 模拟componentWillUnmount
第二个参数(不传默认模拟compontDidMount + componentDidUpdate)
第二个为[]的时候相当于谁都不监听(仅仅模拟compontDidMount)
第二个参数[count],相当于监听count(对特定的state进行监听)
function ReactCom(){
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log('compontDidMount+componentDidUpdate')
return ()=>{
console.log('componentWillUnmount') //模拟componentWillUnmount
}
},[]);
function handelClick(){
setCount(count+1)
}
return (
<div onClick={handelClick}>{count}</div>
)
}
ReactDOM.render(<ReactCom></ReactCom>,document.getElementById('reactId'))