You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SolidJS中响应窗口尺寸变化并触发重新计算?

解决窗口 resize 时未触发计算的问题
  • 核心是正确绑定resize事件,建议搭配防抖函数避免频繁执行计算:
// 防抖函数,控制触发频率,避免窗口拖动时疯狂执行
function debounce(func, delay = 200) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), delay);
  };
}

// 你的宽度计算逻辑
function handleWidthUpdate() {
  const currentWidth = document.body.clientWidth;
  // 替换成你的业务计算代码
  console.log('当前body宽度:', currentWidth);
}

// 确保DOM加载完成后绑定事件
document.addEventListener('DOMContentLoaded', () => {
  // 页面初始化时先执行一次计算
  handleWidthUpdate();
  // 绑定resize事件,用防抖包裹
  window.addEventListener('resize', debounce(handleWidthUpdate));
});
  • 若使用React框架,memo/useMemo仅负责缓存结果,不会自动监听窗口变化,必须配合useEffect绑定事件:
import { useEffect, useState } from 'react';

function LayoutComponent() {
  const [bodyWidth, setBodyWidth] = useState(document.body.clientWidth);

  const updateLayout = () => {
    setBodyWidth(document.body.clientWidth);
    // 这里写依赖宽度的业务计算逻辑
  };

  useEffect(() => {
    const debouncedUpdate = debounce(updateLayout);
    window.addEventListener('resize', debouncedUpdate);
    // 初始执行一次计算
    updateLayout();
    // 组件卸载时清理监听,避免内存泄漏
    return () => window.removeEventListener('resize', debouncedUpdate);
  }, []);

  return <div>当前body宽度: {bodyWidth}</div>;
}

// 复用防抖函数
function debounce(func, delay = 200) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), delay);
  };
}
  • 排查宽度取值是否准确:如果document.body.clientWidth不符合预期,可尝试document.documentElement.clientWidth(获取视口宽度),部分场景下body的margin、padding样式会影响其clientWidth值。

  • 检查是否有其他代码移除了resize监听:若绑定事件后失效,排查是否有其他逻辑调用window.removeEventListener('resize', ...),意外移除了你的监听。

内容的提问来源于stack exchange,提问作者Nic Estrada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:45:19