react中hooks的使用方法

越努力,越幸運!!!發表於2020-10-09

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>
  )
}

相關文章