css - 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?
解决方案
您可以使用材质 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>
);
}
}
推荐阅读
- mongodb - 我的 mongo 没有显示在 C 盘
- r - 如何在 glmnet 中绘制正确的标签?
- python - 否则 ok 运行代码不会在 systemd 下运行
- swift - 在 Swift 4 中以编程方式创建 UIButton 但出现错误
- php - 警告:mysqli_query():第 15 行 C:\xampp\htdocs\IT\Adsware.com\recover.php 中的空查询
- ios - iOS 11 应用程序未唤醒推送通知
- android - Android-水平渐变进度条显示完整进度
- angular - 如何在 Angular 6 中使用 mat-table 仅将未选中的行存储在数组中?
- ffmpeg - 使用 ffmpeg 创建缩放垫效果,但不是黑色背景而是图像背景?
- php - 无法在 cookie 中存储与变量相同的随机字符串