我正在 React 創(chuàng)建一些按鈕,觸發(fā)從一個(gè)到下一個(gè)的狀態(tài)更改。我的一些按鈕具有三種狀態(tài),由枚舉表示。這三種狀態(tài)應(yīng)按連續(xù)順序設(shè)置。當(dāng)達(dá)到最后一個(gè)值時(shí),下一個(gè)操作應(yīng)該再次將狀態(tài)設(shè)置回枚舉的第一個(gè)值。實(shí)現(xiàn)這個(gè)的巧妙方法是什么?
import { create } from 'zustand' import { devtools, persist, createJSONStorage } from 'zustand/middleware' import { BackgroundVariant as Background } from 'reactflow'; function nextBackground(background: Background): Background { switch (background) { case Background.Dots: return Background.Cross; case Background.Cross: return Background.Lines; default: return Background.Dots; }; }; interface MenuState { background: Background; toggleBackground: () => void; } export const useMenuStore = create<MenuState>()( devtools( persist( (set) => ({ background: Background.Dots, toggleBackground: () => set((state) => ({ background: nextBackground(state.background) })) }), { name: 'menu-storage', storage: createJSONStorage(() => localStorage), } ) ) );
下面是一個(gè)函數(shù)的示例,它接受任何枚舉并將返回下一個(gè)值或第一個(gè)值(如果是最后一個(gè)值):
function getNextEnumValue>(enumObj: T, currentValue: T[keyof T]): T[keyof T] { const enumValues = Object.values(enumObj); const enumKeys = Object.keys(enumObj) as (keyof T)[]; const currentIndex = enumKeys.findIndex(key => enumObj[key] === currentValue); if (currentIndex === -1) { throw new Error(`Invalid enum value: ${currentValue}`); } const nextIndex = currentIndex + 1; if (nextIndex === enumKeys.length) { return enumObj[enumKeys[0]]; } const nextValue = enumObj[enumKeys[nextIndex]]; if (!enumValues.includes(nextValue)) { throw new Error(`Invalid enum value: ${nextValue}`); } return nextValue; }