今天就來玩玩含Router的Steps
在設定menu的地方增加一個path
<Route path='/steps2/:path?' Component={Steps2Compnent} />
再來就是花式玩法
主要點擊後不是直接改變 ActiveIndex 而是用 useNavigate 改變路徑
針對改變路徑再改變ActiveIndex
import React, { useState, useEffect } from 'react';
import { Steps } from 'primereact/steps';
import { MenuItem } from 'primereact/menuitem';
import { useParams, useSearchParams, useNavigate } from 'react-router-dom';
const Steps2Compnent: React.FC = () => {
const [activeIndex, setActiveIndex] = useState<number>(0);
const [activeIndex1, setActiveIndex1] = useState<number>(0);
const [activeIndex2, setActiveIndex2] = useState<number>(0);
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { path } = useParams<{ path: string }>();
const isActive = searchParams.get('active');
useEffect(()=>{
if(path&&isActive!==null&&(path===isActive)){
setActiveIndex2(Number(isActive)-1)
}
if(!!path){
setActiveIndex1(Number(path)-1)
}
if(isActive!==null){
setActiveIndex(Number(isActive)-1)
}
},[path,isActive])
const itemRenderer = (item: MenuItem, itemIndex: number, itemType: number) => {
let isActiveItem = false;
let doFn;
switch (itemType) {
case 1:
isActiveItem = activeIndex >= itemIndex
doFn = () => navigate(`?active=${itemIndex + 1}`)//setActiveIndex(itemIndex);
break;
case 2:
isActiveItem = activeIndex1 >= itemIndex
doFn = () => navigate(`/steps2/${(itemIndex + 1)}`)//setActiveIndex1(itemIndex)
break;
case 3:
isActiveItem = activeIndex2 >= itemIndex
doFn = () => navigate(`/steps2/${(itemIndex + 1)}?active=${itemIndex + 1}`)//setActiveIndex2(itemIndex)
break;
default:
break;
}
const backgroundColor = isActiveItem ? 'var(--primary-color)' : 'var(--surface-b)';
const textColor = isActiveItem ? 'var(--surface-b)' : 'var(--text-color-secondary)';
return (
<span
style={{ backgroundColor: backgroundColor, color: textColor }}
onClick={doFn}
>
<i className={`${item.icon} text-xl`} />
</span>
);
};
const getItems = (type: number): MenuItem[] => {
let inx = 0;
switch (type) {
case 1:
inx = activeIndex;
break;
case 2:
inx = activeIndex1;
break;
case 3:
inx = activeIndex2;
break;
default:
break;
}
return (
[
{
icon: 'pi pi-user',
className: inx > 0 ? 'p-active' : '',
template: (item) => itemRenderer(item, 0, type)
},
{
icon: 'pi pi-calendar',
className: inx > 1 ? 'p-active' : '',
template: (item) => itemRenderer(item, 1, type)
},
{
icon: 'pi pi-check',
className: inx > 2 ? 'p-active' : '',
template: (item) => itemRenderer(item, 2, type)
}
])
};
return (
<div>
<Steps model={getItems(1)} activeIndex={activeIndex} readOnly={false} className="m-2 pt-4" />
<Steps model={getItems(2)} activeIndex={activeIndex1} readOnly={false} className="m-2 pt-4" />
<Steps model={getItems(3)} activeIndex={activeIndex2} readOnly={false} className="m-2 pt-4" />
</div>
)
}
export default Steps2Compnent;
那麼,明天見