You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现两个MUI Switch组件的互斥选中状态?

修复MUI Switch单选状态问题(Reducer模式)

当前代码的问题在于reducer仅更新被点击Switch的状态,未重置另一个Switch的状态,导致两者可同时处于选中状态。要实现单选逻辑,点击任意一个Switch时,需将其设为选中状态,同时将另一个设为未选中。

修改Reducer逻辑

// reducer.js

const actionTypes = {
  toggle_price: 'toggle_price'
}

export const initialState = {
  fastprice: false,
  spotprice: true, 
}

export const toggleReducer = (state, action) => {
  switch (action.type) {
    case actionTypes.toggle_price: {
      const selectedName = action.name;
      // 单选逻辑:选中当前Switch,取消另一个
      return {
        fastprice: selectedName === 'fastprice',
        spotprice: selectedName === 'spotprice'
      };
    }
    default:
      return state;
  }
}

export const useToggler = ({ reducer = toggleReducer } = {}) => {
  const [{ fastprice, spotprice}, dispatch] = useReducer(reducer, initialState)
 
  const togglePrice = (event) => dispatch({ 
    type: actionTypes.toggle_price, 
    name: event.target.name 
  })

  return { togglePrice, fastprice, spotprice }
}

组件代码说明

组件部分无需修改,确保Switch的name属性与状态字段对应即可:

//Component.js
const { togglePrice, spotprice, fastprice } = useToggler()

<FormControlLabel 
  control={<Switch onChange={togglePrice} checked={fastprice} name='fastprice' />}
  label='Switch A' 
/>

<FormControlLabel 
  control={<Switch onChange={togglePrice} checked={spotprice} name='spotprice' />}
  label='Switch B' 
/>

核心逻辑说明

  • 调整后的reducer不再依赖event中的checked值,而是根据点击的Switch名称直接设置唯一选中状态,确保同一时间只有一个Switch处于激活状态。
  • 简化了togglePrice函数的参数传递,仅传递Switch的名称,让reducer逻辑更聚焦于状态切换规则。

内容的提问来源于stack exchange,提问作者John low

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:27:21