如何根据特定的视口宽度有条件地渲染一个React组件?

huangapple go评论96阅读模式
英文:

How to conditionally render a React component based on a specific viewport width?

问题

我使用React构建响应式Web应用程序,我有一个组件,应该仅在特定视口宽度的屏幕上显示。如何根据当前视口宽度有条件地呈现此组件?

我已经尝试阅读文档,但对我来说非常混乱和令人困惑。

英文:

I'm using React to build a responsive web application, and I have a component that should only be displayed on screens with a certain viewport width. How do I conditionally render this component based on the current viewport width?

I have tried to read the documentation, however it was really messy and confusing for me.

答案1

得分: 0

以下是翻译好的内容:

为了根据视口宽度有条件地渲染React组件,您可以结合使用window.innerWidth属性和window.addEventListener方法来监听resize事件。通过这样做,您可以管理组件的状态,根据当前窗口大小来渲染或隐藏它。

import React, { useState, useEffect } from 'react';

const ResponsiveComponent = () => {
  const [isVisible, setIsVisible] = useState(window.innerWidth >= 768);

  useEffect(() => {
    const handleResize = () => {
      setIsVisible(window.innerWidth >= 768);
    };

    window.addEventListener('resize', handleResize);

    // 当组件卸载时清除事件监听器
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return (
    <>
      {isVisible && (
        <div>
          <p>此组件仅在视口宽度为768px或更大时可见</p>
        </div>
      )}
    </>
  );
};

export default ResponsiveComponent;
英文:

In order to conditionally render a React component based on the viewport width, you can use a combination of the window.innerWidth property and the window.addEventListener method to listen for the resize event. By doing so, you can manage the state of your component to render or hide it based on the current window size.

import React, { useState, useEffect } from &#39;react&#39;;

const ResponsiveComponent = () =&gt; {
  const [isVisible, setIsVisible] = useState(window.innerWidth &gt;= 768);

  useEffect(() =&gt; {
    const handleResize = () =&gt; {
      setIsVisible(window.innerWidth &gt;= 768);
    };

    window.addEventListener(&#39;resize&#39;, handleResize);

    // Clean up the event listener when the component is unmounted
    return () =&gt; {
      window.removeEventListener(&#39;resize&#39;, handleResize);
    };
  }, []);

  return (
    &lt;&gt;
      {isVisible &amp;&amp; (
        &lt;div&gt;
          &lt;p&gt;This component is only visible when the viewport width is 768px or larger.&lt;/p&gt;
        &lt;/div&gt;
      )}
    &lt;/&gt;
  );
};

export default ResponsiveComponent;

huangapple
  • 本文由 发表于 2023年7月3日 09:51:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定