码迷,mamicode.com
首页 > 其他好文 > 详细

react 实现自定义的hook

时间:2020-07-23 09:18:57      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:scl   def   get   gets   fine   cti   推荐   key   input   

使用hook封装count计数器

技术图片

import React, { useState, useEffect } from "react";

const useCount = (init = 0, dx = 1) => {
  const [count, setCount] = useState(init);
  const dec = () => setCount(count - dx);
  const inc = () => setCount(count + dx);
  const reset = () => setCount(init);
  return [count, dec, inc, reset];
};

export default () => {
  const [c1, dec1, inc1, reset1] = useCount(18, 1);
  const [c2, dec2, inc2, reset2] = useCount(0, 2);
  return (
    <div>
      <div>
        c1:{c1}
        <button onClick={dec1}>dec1 </button>
        <button onClick={inc1}>inc1 </button>
        <button onClick={reset1}>reset1 </button>
      </div>
      <div>
        c2:{c2}
        <button onClick={dec2}>dec2 </button>
        <button onClick={inc2}>inc2 </button>
        <button onClick={reset2}>reset2 </button>
      </div>
    </div>
  );
};

 

 

封装input

技术图片

import React, { useState, useEffect } from "react";
const useInput = (init = "") => {
  const [value, setValue] = useState(init);

  const bind = { value, onChange: (e) => setValue(e.target.value) };
  const reset = () => setValue(init);
  return [value, bind, reset];
};

export default () => {
  const [value1, bind1, reset1] = useInput("abc");
  const [value2, bind2, reset2] = useInput("123");

  return (
    <div>
      value1: {value1} <br></br> value2: {value2} <br></br>
      <input type="text" {...bind1} /> <br></br>
      <input type="text" {...bind2} /> <br></br>
      <button onClick={reset1}>reset1</button> <br></br>
      <button onClick={reset2}>reset2</button>
    </div>
  );
};

 

 

封装浏览器窗口大小

技术图片

import React, { useState, useEffect } from "react";
const useSize = () => {
  const isClient = typeof window === "object";
  const getSize = () => {
    return {
      width: isClient ? window.innerWidth : undefined,
      height: isClient ? window.innerHeight : undefined,
    };
  };
  const [size, setSize] = useState(getSize());
  useEffect(() => {
    if (!isClient) {
      return false;
    }
    function handleResize() {
      setSize(getSize());
    }
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);
  return size;
};
export default () => {
  const size = useSize();
  return (
    <div>
      size:{size.width},{size.height}
    </div>
  );
};

 

react 实现自定义的hook

标签:scl   def   get   gets   fine   cti   推荐   key   input   

原文地址:https://www.cnblogs.com/98kkkkkkkkkk/p/13363938.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!