【问题标题】:How to get React App change content on the screen when screen width changes屏幕宽度更改时如何在屏幕上获取 React App 更改内容
【发布时间】:2021-03-02 13:01:22
【问题描述】:

我的 React 项目中有某些组件将只为移动设备呈现。

我是这样设置的-

const LandingPage = (props) => {
  const [isMobile, setIsMobile] = useState(false);
  useEffect(() => {
    window.screen.width <= 760 ? setIsMobile(true) : setIsMobile(false);
  }, [window.screen.width]);

   **...Components render here**
}

这样做的问题是,只有在刷新页面后才减小屏幕宽度,才能获得所需的结果。但我希望它在断点到达时自动执行。

我如何做到这一点?

提前致谢。

【问题讨论】:

标签: javascript reactjs web browser


【解决方案1】:

您可以使用window.onresize 来检测窗口大小的变化,然后将值与window.innerWidth 进行比较

const LandingPage = (props) => {
    
    const [isMobile, setIsMobile] = useState(false);

    useEffect(() => {
      window.screen.width <= 760 ? setIsMobile(true) : setIsMobile(false);
    }, [window.screen.width]);

    function detectWindowSize() {
        window.innerWidth <= 760 ? setIsMobile(true) : setIsMobile(false);        
    }
    
    window.onresize = detectWindowSize;

    console.log(isMobile)

     return(
         <div>

         </div>
     )
}

【讨论】:

  • 我试过这个,我的应用程序在我添加这个代码后没有加载。这只是一个空白的白色屏幕显示
  • useEffect() 中添加后,行为与之前相同
  • 你需要把它放在useEffect之外。我编辑了代码
  • 谢谢,我正在这样做window.onresize = detectWindowSize()。这是造成问题的原因
【解决方案2】:

您希望通过检查用户是从移动设备还是桌面设备访问来在页面加载时为用户做出决定。

当屏幕分辨率发生变化时在桌面上加载移动组件并不是最好的方法,因为这是一个非常有限的用例。在使用您的 web 应用程序时,没有多少桌面用户会将他们的窗口拉得那么小。但您绝对可以使用 CSS 作为后备,同时仅向移动用户提供移动视图和组件。

【讨论】:

    猜你喜欢
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多