У меня есть фильтр для телефонных номеров, как здесь:
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 handleChangeEvent = (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 = {handleChangeEvent}
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}
/>
);
};
Спасибо! Однако мне пришлось сделать две небольшие поправки: условие
hasCountryCode
является логической противоположностью. Также перед обращением кevent.target.value
я проверил, еслиevent.target
не являетсяundefined
(и если этоundefined
я звонюonChange("")
, чтобы сработал сброс). Спасибо!