javascript - 如何根据react.js中的宽度显示特定数量的div?
问题描述
我正在开发一个组件,它是一种带有箭头的画廊,可以“滑动”它。基本上默认情况下它显示六次潜水,每一次潜水都是带有品牌名称的图像。我希望它根据屏幕宽度看起来有所不同。它应该在大型桌面上显示 6 个 div(或图像),在中型桌面上显示 4 个,在小型桌面上显示 2 个。我想要一种不同于媒体查询的方法。我是 react.js 的新手,因此我们将不胜感激任何提示和帮助。
import React from 'react';
import PropTypes from 'prop-types';
import BrandsBox from '../../common/BrandBox/BrandBox';
import styles from './Brands.module.scss';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faChevronLeft, faChevronRight } from '@fortawesome/free-solid-svg-icons';
class Brands extends React.Component {
state = {
activeBrands: 6,
startBrandDisplay: 0,
};
render() {
const { brands } = this.props;
const { activeBrands } = this.state;
const brandsToDisplay = brands.slice(this.state.startBrandDisplayy, activeBrands+this.state.startBrandDisplay);
return (
<div className={'container'}>
<div className={styles.componentContainer}>
<div
onClick={() => {
this.setState({
...this.state,
startBrandDisplay: this.state.startBrandDisplay-1
})
}}
className={styles.swipe}>
<FontAwesomeIcon icon={faChevronLeft} className={styles.icon} />
</div>
{ brandsToDisplay.map(brands => (
<div id ={brands.id} key={brands.id} className={styles.brandContainer}>
<BrandsBox {...brands} />
</div>
))}
<div
onClick={() => {
this.setState({
...this.state,
startBrandDisplay: this.state.startBrandDisplay+1
})
}}
className={styles.swipe}>
<FontAwesomeIcon icon={faChevronRight} className={styles.icon} />
</div>
</div>
</div>
);
}
}
Brands.propTypes = {
brands: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.number,
name: PropTypes.string,
image: PropTypes.string,
})
),
};
export default Brands;
解决方案
您可以创建一个状态变量来存储设备(台式机、移动设备、平板电脑)。
然后您可以添加一个 EventListener 来调整窗口大小,并根据内部宽度将设备名称分配给状态。
现在,您可以根据设备名称为您的 Parent Div 指定类。
function App() {
const [device, setDevice] = useState("")
function handleResize() {
const width = window.innerWidth
// Now check here what is the width and assign the device name
}
useEffect(() => {
window.addEventListener("resize", "handleResize");
})
}
推荐阅读
- android - 具有渐变颜色和圆角的边框描边
- linux - 如何添加和排序特定行的文本行?
- solr - 当 master 中未启用软提交时 SOLR 执行完整复制复制
- dart - 基于列表创建小部件
- python - 如何将 json 行转换为复合键的 hashmap?
- react-native - 如何在 React Native 中备份/恢复 SQLite 数据库
- powershell - 无法在 Windows Server 2012 R2 Standard 上运行 PowerShell 脚本
- javascript - 在另一个 JS 文件中引用 JS 文件(Appium)
- javascript - 无法进行模态验证
- select - Angular 6 无法从提供的对象中自动选择/绑定下拉列表值