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>
	)
}
相关推荐
超级大只老咪21 小时前
字段行居中(HTML基础语法)
前端·css·html
IT_陈寒21 小时前
Python开发者必看!10个高效数据处理技巧让你的Pandas代码提速300%
前端·人工智能·后端
只_只21 小时前
npm install sqlite3时报错解决
前端·npm·node.js
FuckPatience1 天前
Vue ASP.Net Core WebApi 前后端传参
前端·javascript·vue.js
数字冰雹1 天前
图观 流渲染打包服务器
服务器·前端·github·数据可视化
JarvanMo1 天前
Flutter:我在网上看到了一个超炫的动画边框,于是我在 Flutter 里把它实现了出来
前端
returnfalse1 天前
前端性能优化-第三篇(JavaScript执行优化)
前端·性能优化
yuzhiboyouye1 天前
前端架构师,是架构什么
前端·架构
全马必破三1 天前
Buffer:Node.js 里处理二进制数据的 “小工具”
前端·node.js
web安全工具库1 天前
Linux 高手进阶:Vim 核心模式与分屏操作详解
linux·运维·服务器·前端·数据库