javascript - 是否可以在不同的屏幕尺寸上渲染不同的 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。有没有办法让这个工作与反应组件一起工作,或者有没有其他方法可以工作?
解决方案
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 />
</>
)
}
}
推荐阅读
- django - 如何将 Django 2.0 url() 转换为 path()
- javascript - 如何获取具有特定类和数据属性的选择标签的值?
- c++ - 将 operator<< 与 boost iostreams 压缩过滤器一起使用
- python - 如何显示 .context 导入中的所有可用选项
- terminal - 在 Mojave 中读取终端的 MOTD 消息
- python - 当我在 matplot 中绘制条形图时,如何自定义 yticks 的刻度?
- android - 使用警报管理器定期获取纬度和经度
- ember.js - 是否可以将多个参数传递给 Ember Power Select 中的 onChange 操作?
- regex - 是否有使用熊猫从excel表格中的字符串中分离字母和整数的代码?
- kubernetes - 虚拟机之间的 Calico 作为 Kubernetes 节点