简体   繁体   English

无法更改 MUI v5 TextField 中的十进制值

[英]Unable to change decimal value in MUI v5 TextField

I tried to display decimal value 1.0 in the MUI5's TextField component.我试图在 MUI5 的TextField组件中显示十进制值1.0 I'm able to change its value only with the icons in the TextField but not when I try to input any value.我只能使用TextField的图标更改其值,但不能在尝试输入任何值时更改。 Backspace does not seem to work.退格键似乎不起作用。

Excerpt from my code摘自我的代码

export default function App() {
  const [value, setValue] = useState(1);
  const handleChange = (e) => {
    setValue(e.target.value);
  };
  return (
    <div className="App">
      <TextField
        fullWidth
        variant="outlined"
        id="value"
        name="value"
        type="number"
        label="Decimal Value"
        value={parseFloat(value).toFixed(1)}
        onChange={handleChange}
      />
    </div>
  );
}

I created a working example using CodeSandbox .我使用CodeSandbox创建了一个工作示例。 Could anyone please help?有人可以帮忙吗?

Try formatting the value in onBlur instead of onChange .尝试在onBlur而不是onChange格式化值。 When you type backspace in onChange the value is 1. but is formatted to 1.0 anyway in the next render and undo your work:当您在onChange键入退格键时,该值为1.但在下一次渲染中无论如何都将其格式化为1.0并撤消您的工作:

<TextField
  type="number"
  inputProps={{
    maxLength: 13,
    step: '1',
  }}
  value={value}
  onChange={handleChange}
  onBlur={(e) => setValue(parseFloat(e.target.value).toFixed(1))}
/>

代码沙盒演示

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

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