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>
	)
}
相关推荐
携欢3 分钟前
PortSwigger靶场之Reflected XSS into attribute with angle brackets HTML-encoded通关秘籍
前端·xss
海海思思5 分钟前
Redux Toolkit的前世今生:从繁琐到简洁的状态管理革命
react.js·redux
小爱同学_6 分钟前
React知识:useState和useRef的使用
前端·react.js
再学一点就睡14 分钟前
双 Token 认证机制:从原理到实践的完整实现
前端·javascript·后端
wallflower202016 分钟前
滑动窗口算法在前端开发中的探索与应用
前端·算法
蚂蚁绊大象16 分钟前
flutter第二话题-布局约束
前端
龙在天18 分钟前
我是前端,scss颜色函数你用过吗?
前端
Mapmost25 分钟前
单体化解锁3DGS场景深层交互价值,让3DGS模型真正被用起来!
前端
幻灵尔依1 小时前
前端编码统一规范
javascript·vue.js·代码规范
欢脱的小猴子1 小时前
VUE3加载cesium,导入czml的星座后页面卡死BUG 修复
前端·vue.js·bug