简体   繁体   English

如何根据react.js中的宽度显示特定数量的div?

[英]How to display specific number of divs depending on width in react.js?

I am working on a component which is a kind of gallery with arrows to "slide" it.我正在开发一个组件,它是一种带有箭头的画廊,可以“滑动”它。 Basically by default it shows six dives, each of whish is an image with a brand name.基本上默认情况下它显示六次潜水,每一次潜水都是带有品牌名称的图像。 I would like it to look differently depending on a screen width.我希望它根据屏幕宽度看起来有所不同。 It should show 6 divs (or images) on large desktops, 4 on medium and 2 on small ones.它应该在大型桌面上显示 6 个 div(或图像),在中型桌面上显示 4 个,在小型桌面上显示 2 个。 I would like an approach different than media query.我想要一种不同于媒体查询的方法。 I am new to react.js, so any tips and help will be appreciated.我是 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;

You can create a state variable to store the device(desktop, mobile, tablet).您可以创建一个 state 变量来存储设备(台式机、移动设备、平板电脑)。

And then you can add an EventListener for window resize and assign the device name to state based on the inner width.然后您可以为 window 添加一个 EventListener 调整大小并根据内部宽度将设备名称分配给 state。

Now based on the device name you can specify the class to your Parent Div.现在根据设备名称,您可以将 class 指定给您的 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");
})

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM