在反应中实现三状态切换的最佳方法?
P粉928591383
P粉928591383 2024-04-06 13:51:32
0
1
411

我正在 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学习者快速成长!