【问题标题】:Scroll between view without React Router在没有 React Router 的视图之间滚动
【发布时间】:2021-05-21 15:40:37
【问题描述】:

我的 React 应用程序中的组件按它们在索引中的位置呈现,就像一个步进器。

StackBlitz 上的完整示例:https://stackblitz.com/edit/react-otwg1l?file=src/Comp3.jsx

App.js

const steps = [
    {
      id: 'location',
      component: StepLocation,
    },
    {
      id: 'questions',
      component: StepQuestions,
    },
    {
      id: 'appointment',
      component: StepDate,
    },
]

       return (
         <Step steps={steps} />
       )
// remaning code

steps 作为道具传递到我的主要步进器组件中 Step.js

import React from 'react';
import { useStep } from 'react-hooks-helper';

const Step = ({ steps = {} }) => {
  const { step, navigation, index } = useStep({ initialStep: 0, steps });
  const { id } = step;
  const props = { navigation, index };

  const Component = steps.find((innerStep) => innerStep.id === id).component;
  return <Component {...props} steps={steps} />;
};

export default Step;

步进器可以工作,但是当我在步骤之间导航时,我必须滚动回页面顶部。我知道我需要创建滚动到顶部功能或 CSS 转换,但由于我的应用程序不使用 react-router 在视图之间导航,我该如何添加这个功能/我应该把它放在哪里?

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    您可以使用 vanilla JS 制作滚动到顶部按钮。这可以很容易地集成到您的组件中。将其添加到 useEffect whit 步骤中作为索引,以使其在每次切换步骤时都能正常工作

    滚动到顶部选项请参见:https://www.w3schools.com/howto/howto_js_scroll_to_top.asp

    【讨论】:

      【解决方案2】:

      我假设您有一个组件来处理当前步骤。在这种情况下,您可以在每次所选步骤更改时处理 useEffect 块中的滚动位置:

      const [step, setStep] = useEffect(value);
      
      useEffect(()=> {
        window.scrollTo(0,0);
      }, [step]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-18
        • 1970-01-01
        • 1970-01-01
        • 2012-09-03
        相关资源
        最近更新 更多