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>
	)
}
相关推荐
用户7678797737325 分钟前
后端转全栈之Next.js SEO优化
react.js·next.js
源猿人13 分钟前
企业级文件浏览系统的Vue实现:架构设计与最佳实践
前端·javascript·数据可视化
红红大虾13 分钟前
Defold引擎中关于CollectionProxy的使用
前端·游戏开发
RoyLin21 分钟前
TypeScript设计模式:迭代器模式
javascript·后端·node.js
xw51 小时前
uni-app中v-if使用”异常”
前端·uni-app
!win !1 小时前
uni-app中v-if使用”异常”
前端·uni-app
IT_陈寒2 小时前
Java 性能优化:5个被低估的JVM参数让你的应用吞吐量提升50%
前端·人工智能·后端
南囝coding2 小时前
《独立开发者精选工具》第 018 期
前端·后端
小桥风满袖2 小时前
极简三分钟ES6 - ES9中for await of
前端·javascript