自定义hooks
import React from 'react'
import {useWindowSize} from './hooks'
const Parent = (props) => {
const [width,height] = useWindowSize()
return (
<div>
size: {width}*{height}
</div>
)
}
function App(){
return (
<div className='App'>
<Parent/>
</div>
)
}
import {useEffect,useState} from 'react'
export const useWindowSize = ()=>{
const [width,setWidth] = useState('0px');
const [height,setHeight] = useState('0px');
useEffect(()=>{
setWidth(document.documentElement.clientWidth+'px');
setHeidth(document.documentElement.clientHeight+'px');
},[])
useEffect(()=>{
const handleResize=()=>{
setWidth(document.documentElement.clientWidth+'px');
setHeidth(document.documentElement.clientHeight+'px');
}
window.addEventListener('resize',handleResize,false)
return ()=>{
window.removeEventListener('resize',handleResize,false)
}
},[])
return [width,height]
}
useReducer实现,useState的实现是基于useReducer
import React,{useReducer} from 'react'
const reducer = (state,action)=>{
switch(action.type){
case 'ADD'
return state+1;
case 'SUB'
return state-1;
default:
return state
}
}
const Child=()=>{
const [count,dispatch] = useReducer(reducer,10);
return (
<div>
child: count: {count}
<button onClick={()=>dispatch({type:'ADD'})}>+1</button>
<button onClick={()=>dispatch({type:'SUB'})}>-1</button>
</div>
)
}
const Parent=()=>{
return <div>parent:<Child/></div>
}
function App(){
return (
<div className='App'>
<Parent/>
</div>
)
}
useReducer和useContext一起使用
import React,{useReducer,useContext} from 'react'
const Ctx = React.createContext(null)
const reducer = (state,action)=>{
switch(action.type){
case 'ADD'
return state+1;
case 'SUB'
return state-1;
default:
return state
}
}
const Child=()=>{
const [count,dispatch] = useContext(Ctx);
return (
<div>
child: count: {count}
<button onClick={()=>dispatch({type:'ADD'})}>+1</button>
<button onClick={()=>dispatch({type:'SUB'})}>-1</button>
</div>
)
}
const Parent=()=>{
return (
<div>
parent:{count}
<Child/>
</div>
)
}
function App(){
const [count,dispatch] = useReducer(reducer,20)
return (
<Ctx.Provider value ={[count,dispatch]}>
<div className='App'>
<Parent/>
</div>
</Ctx.Provider>
)
}