首页 > 解决方案 > 是否可以在不同的屏幕尺寸上渲染不同的 React 组件

问题描述

我想使用将在不同断点处呈现的不同组件。我试着用 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);

和CSS

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

和反应响应

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

但似乎它们只适用于普通的 html。有没有办法让这个工作与反应组件一起工作,或者有没有其他方法可以工作?

标签: javascriptreactjsresponsive-designmaterial-ui

解决方案


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 />
          </>
      )
    }
}

推荐阅读