react中hooks的使用方法
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>
)
}
相關文章
- [react] hooksReactHook
- React HooksReactHook
- React Hooks 的用法ReactHook
- React Hooks的理解ReactHook
- react之react HooksReactHook
- React Hooks 梳理ReactHook
- 探React HooksReactHook
- 理解 React HooksReactHook
- Why React HooksReactHook
- React Hooks (Proposal)ReactHook
- React Hooks 指北ReactHook
- React16.8中Hooks詳解ReactHook
- react hooks 的簡單使用ReactHook
- 在 React 專案中全量使用 HooksReactHook
- 在 React Hooks 中如何請求資料?ReactHook
- 實現 React HooksReactHook
- React Hooks總結ReactHook
- 淺談React HooksReactHook
- React Hooks 札記ReactHook
- 精讀《React Hooks》ReactHook
- 擁抱 React HooksReactHook
- React Hooks 深入系列ReactHook
- React hooks實踐ReactHook
- [譯] 理解 React HooksReactHook
- React Native 的未來與React HooksReact NativeHook
- 在專案中的更換 React Hooks 注意事項ReactHook
- 【譯】如何在React Hooks中獲取資料?ReactHook
- [譯] 在 React Hooks 中如何請求資料?ReactHook
- React Hooks的學習筆記ReactHook筆記
- 從Mixin到hooks,談談對React16.7.0-alpha中即將引入的hooks的理解HookReact
- React Hooks:初探·實踐ReactHook
- React Hooks 入門教程ReactHook
- 淺談 React Hooks(一)ReactHook
- React Hooks-概覽ReactHook
- React Hooks 使用詳解ReactHook
- 初探React Hooks & SSR改造ReactHook
- 淺談 React Hooks(二)ReactHook
- React-hooks 簡介ReactHook