简体   繁体   English

是否可以在不同的屏幕尺寸上渲染不同的 React 组件

[英]Is it possible to render different React components on different screen sizes

I want to use different components that will render at different breakpoints.我想使用将在不同断点处呈现的不同组件。 I tried to do it with Material-UI我试着用 Material-UI 来做

import withWidth, { isWidthUp } from '@material-ui/core/withWidth';

function MyComponent(props) {
  if (isWidthUp('sm', props.width)) {
    return <NavBarMedium/>
           <HomePageMedium/>
  }

  return   <NavBarSmall/>
           <HomePageSmall/>
}

export default withWidth()(MyComponent);

and css和 css

//Any component with className display-small will not be displayed above 600px 
@media (max-width: 600px) {
  .display-small{
    display: none;
  }
}

and React-responsive和反应响应

<MediaQuery query="(max-device-width: 600px)">
  <NavBarSmall/>
  <HomePageSmall/>
</MediaQuery>

But it seems they only work with normal html.但似乎它们只适用于普通的 html。 Is there a way to make this work with react components or are there any other ways that this would work?有没有办法让这个工作与反应组件一起工作,或者有没有其他方法可以工作?

function MyComponent(props) {
    let isMobile = useRef(false);
    const [mobile, setMobile] = useState(false);

    useEffect(() => {
        const resize = () => {
            if(window.innerWidth > 600) {
                if(isMobile.current) {
                    isMobile.current = false;
                    setMobile(false);
                }
            } 
            else {
                if(!isMobile.current) {
                    isMobile.current = true;
                    setMobile(true)
                }
            }
         }

        window.addEventListener("resize",  resize);
        
        return () => window.removeListener("resize", resize);

    }, [])


    if (!isMobile.current) { /* or !mobile (state variable) */
      return (
          <> 
             <NavBarMedium />
             <HomePageMedium />
          </>
      )
    }
    else {
      return (
          <> 
             <NavBarSmall />
             <HomePageSmall />
          </>
      )
    }
}

I recommend Material ui media query hooks我推荐 Material ui 媒体查询钩子

https://material-ui.com/es/components/use-media-query/ https://material-ui.com/es/components/use-media-query/

next code show how i use:下一个代码显示我如何使用:

export default function MainWraper() {

  // 0px  xs   600px  sm  960px lg   1280px xl  1920px
  const phone =  useMediaQuery("(max-width: 460px)");
  const tablet =  useMediaQuery("(min-width: 451px) and (max-width: 960px)");
  const desktop =  useMediaQuery("(min-width: 961px)");


  if(phone) return (<phonewrapper/>);
  if(tablet) return (<tabletwrapper/>);
  if(desktop) return (<desktoprapper/>);


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM