我试图在屏幕仅用于移动设备时隐藏一个Carousel组件,并将其显示在平板电脑或更大的屏幕上。最好的方法是什么?我使用的是bootstrap。
为了简单起见,下面是我的代码的编辑版本。如你所见,这是我的主页,在顶部。我想把这个隐藏在手机版本中。谢谢你的帮忙!
import React from 'react'
import { Container, Row, Col } from 'react-bootstrap';
import { HomeStyled } from './style';
import HomePageCarousel from '../Carousel';
const Home = () => {
return (
<>
**<HomePageCarousel/>**
<HomeStyled>
<Container fluid>
<Row>
<Col>
</Col>
</Row>
<Row>
</Row>
</Container>
</HomeStyled>
</>
)
}
export default Home;下面是CSS,我在其中使用了styled component。
import styled from 'styled-components';
export const HomeStyled = styled.section`
@media screen and (min-width: 320px) and (max-width: 576px) {
img,
p {
display: none;
}
}
.left-alignment {
display: flex;
flex-direction: column;
margin-top: 140px;
}
img {
height: 300px;
margin: auto;
}
.right-alignment {
display: flex;
flex-direction: row;
justify-content: flex-end;
align-items: flex-end;
font-size: 1.2rem;
font-weight: 400;
margin: 0 auto;
}
.text-alignment {
display: flex;
flex-direction: column;
justify-content: flex-end;
align-items: flex-end;
font-size: 1.2rem;
font-weight: 400;
margin-left: 50px;
//margin: 0 auto;
}发布于 2021-04-26 20:25:21
执行此操作的最有效的方法是使用matchMedia API:https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
在React中,它将如下所示:
const useMatchMedia = (mediaQuery, initialValue) => {
const [isMatching, setIsMatching] = useState(initialValue)
useEffect(() => {
const watcher = window.matchMedia(mediaQuery)
setIsMatching(watcher.matches)
const listener = (matches) => {
setIsMatching(matches.matches)
}
if (watcher.addEventListener) {
watcher.addEventListener('change', listener)
} else {
watcher.addListener(listener)
}
return () => {
if (watcher.removeEventListener) {
return watcher.removeEventListener('change', listener)
} else {
return watcher.removeListener(listener)
}
}
}, [mediaQuery])
return isMatching
}和:
const isDesktopResolution = useMatchMedia('(min-width:992px)', true)
isDesktopResolution && (
<YourComponents />
)编辑:
您的代码将如下所示:
import React from 'react'
import { Container, Row, Col } from 'react-bootstrap';
import { HomeStyled } from './style';
import HomePageCarousel from '../Carousel';
const isDesktopResolution = useMatchMedia('(min-width:992px)', true)
const Home = () => {
return (
<>
{isDesktopResolution && (
<HomePageCarousel/>
)}
<HomeStyled>
<Container fluid>
<Row>
<Col>
</Col>
</Row>
<Row>
</Row>
</Container>
</HomeStyled>
</>
)
}
export default Home;发布于 2021-04-26 20:25:42
在您的css中:
@media (max-width: 600px) {
.element-to-hide {
display: none;
}
}更棘手的一点(检测现代的触摸式移动设备):
@media only screen and (hover: none) and (pointer: coarse){
.element-to-hide {
display: none;
}
}发布于 2021-04-26 21:51:30
有很多方法可以获取屏幕大小,然后根据屏幕大小有条件地呈现组件
获取屏幕宽度的最简单方法是:-
const Home = () => {
const isMobile = window.screen.width < 600
return (
<>
{ isMobile && < HomePageCarousel /> }
...rest of the code
</>
)
}请记住,当您在浏览器中检查此代码时,请确保在选择移动屏幕后进行刷新,因为这不是一个状态变量,因此不会导致重新呈现。但在移动设备中打开时,它会工作得很好。
https://stackoverflow.com/questions/67266495
复制相似问题