欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > React中Hooks使用

React中Hooks使用

2024/10/23 4:52:25 来源:https://blog.csdn.net/xiaokanfuchen86/article/details/142642433  浏览:    关键词:React中Hooks使用

自定义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>)
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com