【发布时间】:2023-04-07 23:57:01
【问题描述】:
我在 React 中有一个执行 onClick 函数的按钮。我想摆脱按钮,而是在窗口宽度
限制是我不能添加插件。
这是代码的样子...
// Do I need useState, useEffect?
import React, { PureComponent } from "react";
class MainNav extends PureComponent {
state = {
// Does something go here? What goes here and how do I use
// state to execute the function?
navIsCollapsed: false,
};
// this controls rendering of huge images
toggleShowImages() {
this.setState({
navIsCollapsed: !this.state.navIsCollapsed,
});
}
// I want this to be executed by width < 1000
handleSideNavToggle = () => {
this.toggleShowImages(); // controls if React renders components
document.body.classList.toggle("side-nav-closed");
}
这里渲染当前正在执行该功能的按钮。我希望 width
// window width < 1000 should execute this function
<div onClick={this.handleSideNavToggle}>Don't render huge images</div>
// here are the images the function conditionally renders
<should show images &&
<div>Massive huge image</div>
<div>Massive huge image</div>
<div>Massive huge image</div>
>
我可以使用 CSS 媒体查询来显示或隐藏我不想要的大量图像,但这是对 React 的可怕使用。
我已经查看并尝试在 SO 上实现类似的问题,这些问题要么调用插件,要么已过时,要么用例太不同(例如,“根据屏幕大小重新渲染所有内容”)。我也尝试过 React-ify vanilla javascript。这看起来应该很简单,但我做不到。
那里有任何 React 向导可以用干净、有效的解决方案来回答吗?
【问题讨论】:
标签: reactjs media-queries responsive