我正在做一个组件,它是一个带箭头的画廊,可以 "滑动"。基本上默认情况下,它显示六个div,每个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来调整窗口大小,并根据内部宽度将设备名称分配到状态。
现在,基于设备名称,你可以为你的父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");
})
}