什么是 react hook ?
它们不是共享状态的方法,而是共享有状态逻辑的方法
举个简单例子
如下自定义 useWindowSize,可以像调用一个函数一样,调用一个 hook,每个组件的内部状态相互独立
import useWindowSize from './useWindowSize';
const Demo = () => {const {width, height} = useWindowSize();
return (
<div>
<div>width: {width}</div>
<div>height: {height}</div>
</div>
);
};
import {useEffect, useState} from "react";
const useWindowSize = () => {const [state, setState] = useState<{width: number; height: number}>({
width: window.innerWidth,
height: window.innerHeight
});
useEffect(() => {const handler = () => {
setState({
width: window.innerWidth,
height: window.innerHeight
});
};
window.addEventListener('resize', handler);
return () => {window.removeEventListener('resize', handler);
};
}, []);
return state;
};
export default useWindowSize;