国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

在反應(yīng)中實(shí)現(xiàn)三狀態(tài)切換的最佳方法?
P粉928591383
P粉928591383 2024-04-06 13:51:32
0
1
876

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

P粉928591383
P粉928591383

全部回復(fù)(1)
P粉801904089

下面是一個(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;
}
最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板