要想在页面刷新时保持当前步骤条的状态不变,可以使用以下两种方法:

  1. 使用浏览器的本地存储(localStorage或sessionStorage)来存储当前步骤的状态,然后在页面加载时读取存储的状态并更新步骤条的 current 属性。
// 在步骤条组件中设置本地存储
import React, { useEffect } from 'react';
import { Steps } from 'antd';

const { Step } = Steps;

const MySteps = () => {
  useEffect(() => {
    // 读取本地存储的状态
    const currentStep = localStorage.getItem('currentStep');
    if (currentStep) {
      // 更新步骤条的 current 属性
      setCurrent(Number(currentStep));
    }
  }, []);

  const [current, setCurrent] = useState(0);

  // 监听 current 属性的变化,更新本地存储的状态
  useEffect(() => {
    localStorage.setItem('currentStep', current);
  }, [current]);

  return (
    <Steps current={current}>
      <Step title='Step 1' />
      <Step title='Step 2' />
      <Step title='Step 3' />
    </Steps>
  );
};

export default MySteps;
  1. 使用 React 的路由库(如 react-router)来管理页面的路由,将步骤条作为路由的一部分,通过路由的路径来确定当前步骤的状态。
// 使用 react-router 来管理页面路由
import React from 'react';
import { BrowserRouter as Router, Switch, Route, Link, Redirect } from 'react-router-dom';
import { Steps } from 'antd';

const { Step } = Steps;

const MySteps = () => {
  return (
    <Router>
      <Steps current={getCurrentStep()}>  
        <Step title='Step 1' />
        <Step title='Step 2' />
        <Step title='Step 3' />
      </Steps>
      <Switch>
        <Route path='/step1'>
          {/* Step 1 的内容 */}
        </Route>
        <Route path='/step2'>
          {/* Step 2 的内容 */}
        </Route>
        <Route path='/step3'>
          {/* Step 3 的内容 */}
        </Route>
        <Redirect to='/step1' />
      </Switch>
    </Router>
  );
};

// 根据当前路由路径确定当前步骤的状态
const getCurrentStep = () => {
  const pathname = window.location.pathname;
  if (pathname === '/step1') {
    return 0;
  } else if (pathname === '/step2') {
    return 1;
  } else if (pathname === '/step3') {
    return 2;
  }
};

export default MySteps;

使用以上两种方法之一,即可在页面刷新时保持当前步骤条的状态不变。

Antd Steps 步骤条刷新页面保持 current 不变

原文地址: http://www.cveoy.top/t/topic/pb5q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录