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