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>
	)
}
相关推荐
www_stdio几秒前
拒绝做Git“蜘蛛网”制造者!从分支管理到Rebase,带你走一遍标准开发流
前端·github
Moment2 分钟前
面试爱问底层时,我是怎么读大型前端源码的❓❓❓
前端·javascript·面试
long_songs9 分钟前
纯前端 PNG/JPG 转 PDF 工具(无需服务器,源码分享)
服务器·前端·pdf
rongDang19 分钟前
浏览器模拟发送POST请求
前端·javascript
清汤饺子24 分钟前
OpenSpec:让 AI 编程从"开盲盒"到"先签字再干活"
前端·javascript·后端
用户693717500138424 分钟前
太钻 Android 了,在电鸭刷私活把我自己刷清醒了
android·前端·github
wuhen_n28 分钟前
ReAct模式理论:让AI学会“思考-行动-观察”
前端·javascript·ai编程
han_29 分钟前
JavaScript设计模式(七):迭代器模式实现与应用
前端·javascript·设计模式
SPC的存折35 分钟前
4、Ansible之Playbook变量应用
linux·前端·chrome·ansible
吴佳浩 Alben35 分钟前
Vibe Coding 时代:Vue 消失了还是 React 太强?
前端·vue.js·人工智能·react.js·语言模型·自然语言处理