react中hooks的使用方法
程序员文章站
2022-07-03 15:23:52
...
hooks 它改变了原始的React类的开发方式,改用了函数形式;它改变了复杂的状态操作形式,让程序员用起来更轻松;它改变了一个状态组件的复用性,让组件的复用性大大增加
import React, { Component,useState,useEffect ,useRef} from 'react';
import { HashRouter as Router, Route, NavLink, Redirect, Switch ,useHistory} from "react-router-dom";
class APP extends Component {
render() {
return (
<div>
<Router>
{/* <NavLink to="/">首页</NavLink> |
<NavLink to="/about">关于</NavLink> |
<NavLink to="/login">登录</NavLink> |
<NavLink to="/private">权限</NavLink> | */}
<NavLink to="/hooks">Hooks</NavLink> |
<br/>
<Switch>
{/* <Route path="/" exact component={Home}></Route>
<Route path="/about" exact component={About}></Route>
<Route path="/login" exact component={Login}></Route> */}
<Route path="/hooks" exact component={Hooks}></Route>
{/* <PrivatePage path="/private">
<Private></Private>
</PrivatePage> */}
</Switch>
</Router>
</div>
);
}
}
export default APP;
//自定义
function UseWinSize(){
const [size,setSize]=useState({
width:window.innerWidth,
height:window.innerHeight,
})
const onResize=()=>{
setSize({
width:window.innerWidth,
height:window.innerHeight
})
}
useEffect(()=>{
window.addEventListener('resize',onResize);
return ()=>{
window.removeEventListener('resize',onResize)
}
},[])
return size
}
function Hooks(){
let size=UseWinSize()
const [num,setNum]=useState(0)
const [age,setAge]=useState(20)
let inp=useRef(null)
const setIt=()=>{
setNum(window.parseInt(inp.current.value))
}
useEffect(()=>{
console.log('更新了',num);
return()=>{
console.log('卸载了');
}
},[num])
return(
<div>
<h1>Hooks页面</h1>
<button onClick={()=>setNum(num+1)}>{num}</button>
<button onClick={()=> setAge(age+10)}>年龄:{age}</button>
<p>
宽:{size.width},高:{size.height}
</p>
<p>
<input type="text" ref={inp}/>
<button onClick={setIt}>点击</button>
</p>
</div>
)
}