有没有更好的方法来根据反应应用程序的屏幕尺寸更改样式?

Jak*_*ake 3 javascript reactjs material-ui

我在我的 React 应用程序上使用 Material UI,并且使用 mui 中的 useMediaQuery 和 useTheme。这是我现在拥有的代码。有没有更好的方法来优化更少的代码?两个代码之间只有一些样式变化。

const MainPage = () => {
    const theme = useTheme();
    const isMatch = useMediaQuery(theme.breakpoints.down('md'))
    return (
        <div className='mainPage'>
            {
                isMatch ? (
                    <>
                        <Box sx={{ display: "flex", justifyContent: "center", alignContent: "center", flexDirection: "column", padding: "60px 10px 10px 10px" }}>
                            <Box component="img" src={LandingImage} sx={{ width: "100%" }} />
                            <Box sx={{ paddingTop: 8 }}>
                                <Typography sx={{ fontSize: 26, fontWeight: "bold", fontFamily: "sans-serif", textAlign: "center", paddingBottom: 5 }}>About us</Typography>
                            </Box>
                        </Box>
                    </>
                ) : (
                    <>
                        <Box sx={{ display: "flex", justifyContent: "center", alignContent: "center", flexDirection: "row", paddingTop: 20 }}>
                            <Box component="img" src={LandingImage} />
                            <Box sx={{ width: 700, paddingTop: 8 }}>
                                <Typography sx={{ fontSize: 30, fontWeight: "bold", fontFamily: "sans-serif", textAlign: "center", paddingBottom: 5 }}>About us</Typography>
                            </Box>
                        </Box>
                    </>
                )}
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

Ver*_*era 8

实际上没有必要执行这样的媒体查询,因为sx如果需要,该属性会提供每个断点的自定义。

例如,请注意flexDirection第一个 Box 组件上的样式。直到md断点的一切都得到了column,然后就变成了row

const MainPage = () => {
  const theme = useTheme();
  return (
    <div className='mainPage'>
      <Box sx={{ 
        display: "flex", 
        justifyContent: "center", 
        alignContent: "center", 
        flexDirection: { xs: "column", md: "row" },
        padding: { xs: "60px 10px 10px 10px", md: "20px 0 0 0" } 
      }}>
        <Box 
          component="img" 
          src={LandingImage} 
          sx={{ 
            width: { xs: "100%", md: 'unset' }
        }}/>
        <Box sx={{ 
          paddingTop: 8,
          width: { md: 700 }
        }}>
          <Typography 
            sx={{ 
              fontSize: { xs: 26, md: 30 }, 
              fontWeight: "bold", 
              fontFamily: "sans-serif", 
              textAlign: "center", 
              paddingBottom: 5 
          }}>
            About us
          </Typography>
        </Box>
      </Box>
    </div>
  )
}

Run Code Online (Sandbox Code Playgroud)

https://mui.com/system/basics/#responsive-values