首页 > 解决方案 > 如何根据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;

标签: javascriptreactjsslidergallery

解决方案


您可以创建一个状态变量来存储设备(台式机、移动设备、平板电脑)。

然后您可以添加一个 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");
})

}


推荐阅读