reactjs 滚动时渲染下一个组件

apeeds0o  于 2023-11-18  发布在  React
关注(0)|答案(1)|浏览(99)

我有一个页面,显示了许多组件在一个,组件获取数据,所以它使页面加载相当慢。
我想只显示前2个组件,当滚动到底部显示<Hotels />,然后当滚动到底部的酒店,显示<Nightlife />等。
这是我现在的页面:

'use client';

import { IPageProps } from '@/app/[city]/[lang]/page';
import React from 'react';
import ToVisit from './categories/ToVisit';
import Tops from './categories/Tops';
import Restaurants from './categories/Restaurants';
import Hotels from './categories/Hotels';
import Nightlife from './categories/Nightlife';
import Shopping from './categories/Shopping';
import Activities from './categories/Activities';

function CategoryPlaces({ params }: IPageProps) {
  return (
    <>
      <Tops params={params} />
      <Restaurants params={params} />
      <Hotels params={params} />
      <Nightlife params={params} />
      <Shopping params={params} />
      <Activities params={params} />
      <ToVisit params={params} />
    </>
  );
}

export default CategoryPlaces;

字符串
如何在React中做到这一点?

k2arahey

k2arahey1#

import React, { useState, useEffect } from 'react';
import ToVisit from './categories/ToVisit';
import Tops from './categories/Tops';
import Restaurants from './categories/Restaurants';
import Hotels from './categories/Hotels';
import Nightlife from './categories/Nightlife';
import Shopping from './categories/Shopping';
import Activities from './categories/Activities';

function CategoryPlaces({ params }: IPageProps) {
  const [componentToShow, setComponentToShow] = useState('Tops'); // Initially show Tops and ToVisit
  const components = ['Restaurants', 'Hotels', 'Nightlife', 'Shopping', 'Activities',ToVisit];

  useEffect(() => {
    function handleScroll() {
      const windowHeight = window.innerHeight;
      const scrollY = window.scrollY || window.pageYOffset;
      const bodyHeight = document.body.offsetHeight;

      // Check if scrolled to the bottom
      if (windowHeight + scrollY >= bodyHeight) {
        const nextComponentIndex = components.findIndex(comp => comp === componentToShow) + 1;
        if (nextComponentIndex < components.length) {
          setComponentToShow(components[nextComponentIndex]);
        }
      }
    }

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [componentToShow, components]);

  return (
    <>
      {componentToShow === 'Tops' && <Tops params={params} />}
      {componentToShow === 'Restaurants' && <Restaurants params={params} />}
      {componentToShow === 'Hotels' && <Hotels params={params} />}
      {componentToShow === 'Nightlife' && <Nightlife params={params} />}
      {componentToShow === 'Shopping' && <Shopping params={params} />}
      {componentToShow === 'Activities' && <Activities params={params} />}
      {componentToShow === 'ToVisit' && <ToVisit params={params} />}
    </>
  );
}

export default CategoryPlaces;

字符串

相关问题