首页 > 解决方案 > Reactjs 媒体查询应用

问题描述

我有一个单独的 App.css 文件,它具有全局 css 属性并具有响应性类。问题是我想为不同的设备以不同的方式呈现元素,但似乎无法弄清楚如何做到这一点,因为使用条件并不适用。

import UserItem from "./UserItem";
import Spinner from "../layout/Spinner";
import PropTypes from "prop-types";

const Users = ({ users, loading }) => {
  if (loading) {
    return <Spinner />;
  } else {
    return (
      <div style={userStyle} className='body'>
        {users.map((user) => {
          return <UserItem key={user.id} user={user} />;
        })}
      </div>
    );
  }
};

const windowWidth = window.innerWidth;

Users.propTypes = {
  users: PropTypes.array.isRequired,
  loading: PropTypes.bool.isRequired,
};

const userStyle = {
  display: "grid",
  gridTemplateColumns: "repeat(3, 1fr)",
  gridGap: "1rem",
};

export default Users;

My css @media query which I am trying to apply to effect change on a small device.

/* Mobile Styles */
@media (max-width: 700px) {
  .hide-sm {
    display: none;
  }
}

How do I implement this @media css style so that it can render the page differents through jsx?

标签: cssreactjs

解决方案


您可以使用材质 ui。这将满足您的要求。请检查这个例子:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import { green } from '@material-ui/core/colors';

const useStyles = makeStyles(theme => ({
  root: {
    padding: theme.spacing(1),
    [theme.breakpoints.down('sm')]: {
      backgroundColor: theme.palette.secondary.main,
    },
    [theme.breakpoints.up('md')]: {
      backgroundColor: theme.palette.primary.main,
    },
    [theme.breakpoints.up('lg')]: {
      backgroundColor: green[500],
    },
  },
}));

export default function MediaQuery() {
  const classes = useStyles();
  return (
    <div className={classes.root}>
      <Typography variant="subtitle1">{'down(sm): red'}</Typography>
      <Typography variant="subtitle1">{'up(md): blue'}</Typography>
      <Typography variant="subtitle1">{'up(lg): green'}</Typography>
    </div>
  );
}

材质界面

您也可以使用以下示例。

class Card extends Component {

  constructor() {

    super();

    this.mediaQuery = {
      desktop: 1200,
      tablet: 768,
      phone: 576,
    };

    this.state = {
      windowWidth: null
    };
  }

  componentDidMount() {
    window.addEventListener('resize', () => {
      this.setState({windowWidth: document.body.clientWidth})
    });
  }

  render() {
    return (
      <div style={{
        width: this.state.windowWidth > this.mediaQuery.phone
          ? '50%'
          : '100%',
        //more styling :)
      }}>
        <!-- <Card> contents -->
      </div>
    );
  }
}

资源


推荐阅读