在反應中實現三狀態切換的最佳方法?
P粉928591383
P粉928591383 2024-04-06 13:51:32
0
1
410

我正在 React 建立一些按鈕,觸發從一個到下一個的狀態變更。我的一些按鈕有三種狀態,由枚舉表示。這三種狀態應依連續順序設定。當達到最後一個值時,下一個操作應該再次將狀態設定回枚舉的第一個值。實現這個的巧妙方法是什麼?

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),
      }
    )
  )
);

P粉928591383
P粉928591383

全部回覆(1)
P粉801904089

下面是一個函數的範例,它接受任何枚舉並將傳回下一個值或第一個值(如果是最後一個值):

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;
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!