搜尋

首頁  >  問答  >  主體

在反應中實現三狀態切換的最佳方法?

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

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粉928591383P粉928591383355 天前708

全部回覆(1)我來回復

  • P粉801904089

    P粉8019040892024-04-07 00:43:34

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    function getNextEnumValue<t extends="" record<string,="" string="">>(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;

    }</t>

    回覆
    0
  • 取消回覆