如何实现两个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
相关产品推荐
相关产品推荐

