英文:
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 'react';
const ResponsiveComponent = () => {
const [isVisible, setIsVisible] = useState(window.innerWidth >= 768);
useEffect(() => {
const handleResize = () => {
setIsVisible(window.innerWidth >= 768);
};
window.addEventListener('resize', handleResize);
// Clean up the event listener when the component is unmounted
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return (
<>
{isVisible && (
<div>
<p>This component is only visible when the viewport width is 768px or larger.</p>
</div>
)}
</>
);
};
export default ResponsiveComponent;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论