首页  >  问答  >  正文

点击MUI切换开关时,无法更新显示和值的问题

<p>我在当前项目中使用的Material UI切换开关遇到了问题。当组件加载时,如果我在控制台记录值,初始值是正确的。但是,如果我点击开关,从“是”切换到“否”,开关将正确地渲染显示选择了“否”,控制台记录再次触发,但值仍然显示为“是”。如果我再次点击开关,尝试将其切换回“否”,切换开关只会重新渲染而不会翻转,控制台记录再次触发,值现在更新为“否”。所以基本上第一次点击翻转开关,第二次点击翻转值。我之前使用过相同的切换开关没有问题,所以有人能告诉我需要修复什么才能在单击时翻转开关和值吗?</p> <p><strong>处理输入变化:</strong></p> <pre class="brush:php;toolbar:false;">const handleInputChange = e => { const { name, value } = e.target; setValues({ ...values, [name]: ( typeof value === 'string' ? (value).replace(/ +(?= )/g, '').trimStart() : value ) // 如果值是字符串,则去除前导空格和多个空格 }); };</pre> <p><strong>从表单中调用的开关:</strong></p> <pre class="brush:php;toolbar:false;"><ToggleSwitch onChange={handleInputChange} label1='否' label2='是' name='useForCalcs' value={values.useForCalcs} /></pre> <p><strong>ToggleSwitch组件:</strong></p> <pre class="brush:php;toolbar:false;">import * as React from 'react'; import {Box, Switch, Typography} from '@material-ui/core'; export default function ToggleSwitch(props) { const { label1, label2, name, onChange, value} = props; const [checked, setChecked] = React.useState(false); const convertToEventParams = (name, value) => ({ target: { name, value } }); const curValue = value === 1 ? true : false; const handleSwitch = e => { setChecked(e.target.checked); }; React.useEffect(() => { setChecked(curValue); }, [curValue]); // 每次checked值改变时重新渲染切换开关 const handleChecked = e => { handleSwitch(e); onChange(convertToEventParams(name, (checked === false ? 1 : 0))); // 将True/False转换为1/0值 }; return ( <Box> <Typography> {label1} {<Switch name={name} checked={checked} value={checked} onChange={handleChecked} inputProps={{'aria-label': 'switch'}} />} {label2} </Typography> </Box> ); }</pre> <p><br /></p>
P粉638343995P粉638343995403 天前450

全部回复(1)我来回复

  • P粉298305266

    P粉2983052662023-08-16 10:48:25

    你正在处理ToggleSwitch组件中的状态和选中值。你既有本地状态(checked),又有一个prop(value),你想要将它们同步。

    要解决这个问题,确保开关和值正确同步

    你正在从父组件传递value prop,你可以直接使用该prop来确定开关的状态。 你可以通过删除不必要的状态和效果来简化组件代码。

    你可以直接使用value prop来确定开关的初始状态,并使用onChange函数更新父组件。

    import React from 'react';
    import { Box, Switch, Typography } from '@material-ui/core';
    
    export default function ToggleSwitch(props) {
      const { label1, label2, name, onChange, value } = props;
    
      const handleChecked = () => {
        const newValue = value === 0 ? 1 : 0; // 切换值
        onChange({ target: { name, value: newValue } });
      };
    
      return (
        <Box>
          <Typography>
            {label1}
            <Switch
              name={name}
              checked={value === 1}
              onChange={handleChecked}
              inputProps={{ 'aria-label': 'switch' }}
            />
            {label2}
          </Typography>
        </Box>
      );
    }

    回复
    0
  • 取消回复