react 实现自定义的hook

Posted 98kkkkkkkkkk

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react 实现自定义的hook相关的知识,希望对你有一定的参考价值。

使用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的主要内容,如果未能解决你的问题,请参考以下文章

实现一个自定义 React Hook:useLocalStorageState

实现一个自定义 React Hook:useLocalStorageState

React在工作中对于 Custom React Hooks 一些思考

React在工作中对于 Custom React Hooks 一些思考

只用两个自定义 Hooks 就能替代 React-Redux ?

React-hook-form v7 - 自定义输入警告功能组件不能被赋予参考