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>
	)
}
相关推荐
还是鼠鼠1 小时前
图书管理系统 Axios 源码__新增图书
前端·javascript·vscode·ajax·前端框架·node.js·bootstrap
还是鼠鼠4 小时前
图书管理系统 Axios 源码 __删除图书功能
前端·javascript·vscode·ajax·前端框架·node.js·bootstrap
轻口味4 小时前
Vue.js `Suspense` 和异步组件加载
前端·javascript·vue.js
m0_zj6 小时前
8.[前端开发-CSS]Day08-图形-字体-字体图标-元素定位
前端·css
还是鼠鼠6 小时前
图书管理系统 Axios 源码__编辑图书
前端·javascript·vscode·ajax·前端框架
北极象6 小时前
vue3中el-input无法获得焦点的问题
前端·javascript·vue.js
百度网站快速收录6 小时前
网站快速收录:如何优化网站头部与底部信息?
前端·html·百度快速收录·网站快速收录
Loong_DQX6 小时前
【react+redux】 react使用redux相关内容
前端·react.js·前端框架
GISer_Jing7 小时前
react redux监测值的变化
前端·javascript·react.js
engchina7 小时前
CSS 样式化表格:从基础到高级技巧
前端·css