如何限制 Material UI TextField 中的数字(即使是字符串类型)?

How to restrict numbers (even in String type) from MaterialUI TextField?

考虑以下代码:

<Grid item lg={6} md={6} xs={12} >
     <TextField fullWidth type={'text'} label="Product Color" value={productColor} onChange={(e) => setProductColor(e.target.value)} />
</Grid>

即使设置为输入文字,如何完全防止输入数字,只允许输入A-z或a-z的文字?有什么想法吗?

一种方法是利用您可以将某些道具传递给文本字段并将其与正则表达式结合起来这一事实。这不一定会阻止他们允许输入,但是,如果它包含任何数字,它将阻止提交文本字段。然后你只需要添加错误处理来显示相关的消息

<TextField
  inputProps={{ pattern: "([^0-9]*)" }} error={'Error Message'}
/>

查看文本字段 api here 了解更多详细信息

您可以使用 react-number-format 之类的东西,而不是重新发明轮子。 他们有一个 example in their docs:

<NumberFormat customInput={TextField} format="#### #### #### ####" />

也可以反过来做,给予对 TextField 的更多控制,但需要更多的工作。

import React from "react";

import { InputBaseComponentProps } from "@mui/material";
import NumberFormat from "react-number-format";

export const NumberInput = React.forwardRef<
    NumberFormat,
    InputBaseComponentProps
>((props, ref) => {
    const { onChange, ...other } = props;
    return (
        <NumberFormat
            isNumericString
            {...(other as any)}
            getInputRef={ref}
            onValueChange={(values) =>
                onChange && onChange({ target: { value: values.value } } as any)
            }
        />
    );
});

然后这样使用,注意price值还是字符串

const [price, setPrice] = useState("0");

return <TextField
 value={price}
 onChange={(evt) => setPrice(evt.target.value) }
 InputProps={{
  inputComponent: NumberInput,
  inputProps: {
    decimalSeparator: ",",
    decimalScale: 2,
    fixedDecimalScale: true,
    allowNegative: false,
    prefix: "€ ",
  },
}}

这给你这样的东西:

像这样使用正则表达式:

import { Stack, TextField } from "@mui/material";
import { useState } from "react";

const isLetters = (str) => /^[A-Za-z]*$/.test(str);

export default function IndexPage() {
  const [val, setVal] = useState("");

  const onInputChange = (e) => {
    const { value } = e.target;
    if (isLetters(value)) {
      setVal(value);
    }
  };

  return (
    <Stack spacing={2} padding={2} height={"100vh"}>
      <TextField label="Letters only" value={val} onChange={onInputChange} />
    </Stack>
  );
}