简体   繁体   English

React State 和 MUI TextFields 的奇怪行为

[英]Strange Behavior with React State and MUI TextFields

I have a basic set of code.. That I am trying to toggle:我有一组基本代码..我正在尝试切换:

{(isLinkPhone) ?
    <Box>
        <TextField
            value={phone}
            label="Phone Number"
            disabled
        />
    </Box>
    :
    <Box>
        <TextField
            defaultValue=''
            label="Link for your button *"
        />
    </Box>
}

Basically what I am trying to do is during a toggle of:基本上我想做的是在切换期间:

    const [isLinkPhone, setLinkisPhone] = React.useState(false);

I want to display one or the other.. The issue is that I can't set BOTH value AND defaultValue -- I am having a hard time understanding why React is treating this as the same input that cannot have a controlled and uncontrolled value.我想显示一个或另一个。问题是我无法同时设置valuedefaultValue值——我很难理解为什么 React 将其视为不能具有受控值和不受控值的相同输入。 What I am trying to do is set the field to "nothing -> enabled/editable" if !isLinkPhone -- Else set it to " {phone} -> disabled" -- The issue is that the values "translate" between toggles.我想要做的是将字段设置为“无 -> 启用/可编辑”,如果!isLinkPhone - 否则将其设置为“ {phone} -> 禁用” - 问题是值在切换之间“转换”。

在此处输入图像描述

Is there a better way to go about this? go关于这个有没有更好的办法? I am hesitant to create individual components for fear I will spend the time and get the same result.我对创建单独的组件犹豫不决,因为我担心我会花时间并得到相同的结果。 Can anyone explain why this is happening?谁能解释为什么会这样?

Try this尝试这个

  <Box>
    {isLinkPhone && (
      <TextField value={phone} label="Phone Number" disabled />
    )}

    {!isLinkPhone && (
      <TextField defaultValue="" label="Link for your button *" />
    )}
  </Box>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM