@slotjs/hooks
v0.0.5
Published
@slotjs/hooks for react
Downloads
315
Readme
@slotjs/hooks
@slotjs/hooks 目前提供 useResponsive,用于根据视口宽度动态设置根节点 html 的字体大小,适合基于 rem 的响应式布局。
npm i @slotjs/hooksuseResponsive
useResponsive 会在组件挂载后立即根据当前视口宽度设置一次 html 的 font-size,并在窗口尺寸变化时自动更新。
计算规则如下:
html.style.fontSize = `${baseFontSize * Math.min(clientWidth / baseWidth, 2)}px`;也就是说:
- 设计稿宽度等于
baseWidth时,根字体大小为baseFontSize - 页面变宽时会按比例放大,但最大只放大到
2x - 页面变窄时会按比例缩小
TypeScript 签名
function useResponsive(baseWidth?: number, baseFontSize?: number): boolean;参数
| 参数 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| baseWidth | number | 1920 | 设计稿基准宽度 |
| baseFontSize | number | 16 | 设计稿基准宽度下的根字体大小 |
返回值
返回 boolean 类型的 isReady:
false:初始字体大小尚未设置完成true:已经完成首次计算并设置根字体大小
这个返回值适合用来控制首屏渲染,避免依赖 rem 的内容在初始化前出现尺寸闪动。
基础用法
import { useResponsive } from "@slotjs/hooks";
const Index: React.FC = () => {
const isReady = useResponsive();
return isReady ? (
<ContentContainer>content</ContentContainer>
) : (
<FullScreenWrapper>loading</FullScreenWrapper>
);
};自定义设计稿宽度和基准字号
import { useResponsive } from "@slotjs/hooks";
const Page = () => {
const isReady = useResponsive(1440, 20);
if (!isReady) return null;
return <main style={{ fontSize: "1rem" }}>content</main>;
};在上面的例子里:
- 当视口宽度为
1440px时,html根字体大小为20px - 当视口宽度为
720px时,根字体大小为10px - 当视口宽度大于等于
2880px时,根字体大小封顶为40px
使用建议
- 推荐配合
rem单位使用,这样页面元素会随着根字体大小一起缩放 - 该 hook 依赖
window和document,应在浏览器环境中使用 - 如果项目存在 SSR,建议只在客户端渲染阶段调用
