如何根据屏幕尺寸隐藏 React 中的组件?

Imm*_*ggi 12 reactjs

我试图在屏幕仅移动时隐藏轮播组件并将其显示在平板电脑或更大的屏幕中。最好的方法是什么?我正在使用引导程序。

为了简单起见,下面是我的代码的编辑版本。如您所见,这是我的主页,位于顶部。我希望将其隐藏在移动版本中。感谢您的帮助!

import React from 'react'
import { Container, Row, Col } from 'react-bootstrap';
import { HomeStyled } from './style';
import HomePageCarousel from '../Carousel';



const Home = () => {
    
    return (
    <>    
        **<HomePageCarousel/>**
        <HomeStyled>
            <Container fluid>
            <Row>
                <Col>   
                </Col> 
            </Row>
            <Row>
            </Row>
            </Container>
        </HomeStyled>
    </>
    )
}

export default Home;

Run Code Online (Sandbox Code Playgroud)

下面是 CSS,我在其中使用样式组件..

import styled from 'styled-components';

export const HomeStyled = styled.section`

@media screen and (min-width: 320px) and (max-width: 576px) {
    img,
    p   {
        display: none;
    }
}

.left-alignment {
        display: flex;
        flex-direction: column;
        margin-top: 140px;
    }    

img {
    height: 300px;
    margin: auto;
}

.right-alignment {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: flex-end;
    font-size: 1.2rem;
    font-weight: 400;
    margin: 0 auto;
}

.text-alignment {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    align-items: flex-end;
    font-size: 1.2rem;
    font-weight: 400;
    margin-left: 50px;
    //margin: 0 auto;

}
Run Code Online (Sandbox Code Playgroud)

Ami*_*era 12

定义useWindowSize.js自定义钩子以获取当前窗口宽度/高度

import { useState, useEffect } from "react";

// Hook
const useWindowSize = () => {
    // Initialize state with undefined width/height so server and client renders match
    // Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
    const [windowSize, setWindowSize] = useState({
        width: undefined,
        height: undefined
    });

    useEffect(() => {
        // only execute all the code below in client side
        if (typeof window !== "undefined") {
            // Handler to call on window resize
            function handleResize() {
                // Set window width/height to state
                setWindowSize({
                    width: window.innerWidth,
                    height: window.innerHeight
                });
            }

            // Add event listener
            window.addEventListener("resize", handleResize);

            // Call handler right away so state gets updated with initial window size
            handleResize();

            // Remove event listener on cleanup
            return () => window.removeEventListener("resize", handleResize);
        }
    }, []); // Empty array ensures that effect is only run on mount
    return windowSize;
};

export default useWindowSize;
Run Code Online (Sandbox Code Playgroud)

在你的代码中

import React from 'react'
import { Container, Row, Col } from 'react-bootstrap';
import { HomeStyled } from './style';
import HomePageCarousel from '../Carousel';

import useWindowSize from '.path/to/your/hooks/useWindowSize'

const Home = () => {
    
    const size = useWindowSize();    

    return (
    <>    
        {size.width > 600 && <HomePageCarousel/>}
        <HomeStyled>
            <Container fluid>
            <Row>
                <Col>   
                </Col> 
            </Row>
            <Row>
            </Row>
            </Container>
        </HomeStyled>
    </>
    )
}

export default Home;

Run Code Online (Sandbox Code Playgroud)


Bar*_*ski 8

有效的方法是使用 matchMedia API:https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

在 React 中它看起来像这样:

const useMatchMedia = (mediaQuery, initialValue) => {
  const [isMatching, setIsMatching] = useState(initialValue)
  useEffect(() => {
    const watcher = window.matchMedia(mediaQuery)
    setIsMatching(watcher.matches)
    const listener = (matches) => {
      setIsMatching(matches.matches)
    }
    if (watcher.addEventListener) {
      watcher.addEventListener('change', listener)
    } else {
      watcher.addListener(listener)
    }
    return () => {
      if (watcher.removeEventListener) {
        return watcher.removeEventListener('change', listener)
      } else {
        return watcher.removeListener(listener)
      }
    }
  }, [mediaQuery])

  return isMatching
}
Run Code Online (Sandbox Code Playgroud)

和:

const isDesktopResolution = useMatchMedia('(min-width:992px)', true)

isDesktopResolution && (
  <YourComponents />
)
Run Code Online (Sandbox Code Playgroud)

编辑:

代码沙盒

您的代码将如下所示:

import React from 'react'
import { Container, Row, Col } from 'react-bootstrap';
import { HomeStyled } from './style';
import HomePageCarousel from '../Carousel';


const isDesktopResolution = useMatchMedia('(min-width:992px)', true)

const Home = () => {
    
    return (
    <>    
        {isDesktopResolution && (
          <HomePageCarousel/>
        )}
        <HomeStyled>
            <Container fluid>
            <Row>
                <Col>   
                </Col> 
            </Row>
            <Row>
            </Row>
            </Container>
        </HomeStyled>
    </>
    )
}

export default Home;
Run Code Online (Sandbox Code Playgroud)