在解析器中显示通知

Show notification in a parser

我有一个过滤 phone 个数字的过滤器,如下所示:

const UserFilter = (props: any) => <Filter {...props}>
    <TextInput label="Mobile" source="mobile" alwaysOn resettable parse={phoneParser} />
    <TextInput label="E-Mail" source="email" alwaysOn resettable />
</Filter>

我使用解析器将前导零替换为固定的国家/地区代码:

const phoneParser = (value: string) => {
    const needsCountryCode = value.charAt(0)=="0"
    if (needsCountryCode) {
        showNotification(`Mobile number reformatted with country code of Switzerland.`,'warning')
    }
    return needsCountryCode ? "+41"+value.substring(1):value;
};

现在,我想在每次发生这种替换时通知用户(通常只发生一次)。我尝试使用 useNotify 挂钩,但它不是功能组件,然后我尝试了 showNotification 函数,但它什么也没做。这在解析器函数中甚至可能吗?

我建议您为此创建自定义输入。像这样:

import { FieldTitle, InputHelperText, ResettableTextField, useNotify, useInput } from "react-admin";

const hasCountryCode = (value) => value.charAt(0) === "0";
const addCountryCode = (value) => "+41" + value.substring(1);

export const PhoneInput = (props) => {
    const { helperText, label, source, resource, ...restProps } = props;
    const {
      input: { name, onChange, ...rest },
      meta: { error, submitError, touched },
      isRequired,
    } = useInput(props);
    const notify = useNotify();

    const handleChange = (event) => {
        const value = event.target.value;
        if (hasCountryCode(value)) {
            onChange(value);
        } else {
            notify(
                `Mobile number reformatted with country code of Switzerland.`,
                { type: "warning" }
            );
            onChange(addCountryCode(value));
        }
    };
    
    return (
      <ResettableTextField
        name={name}
        onChange={handleChange}
        label={
          label !== "" &&
          label !== false && (
            <FieldTitle
              label={label}
              source={source}
              resource={resource}
              isRequired={isRequired}
            />
          )
        }
        error={!!(touched && (error || submitError))}
        helperText={
          <InputHelperText
            touched={touched}
            error={error || submitError}
            helperText={helperText}
          />
        }
        {...rest}
        {...restProps}
      />
    );
};