WEB/src/components/InternationalPhoneInput.tsx

85 lines
1.8 KiB
TypeScript

import { Input, Select } from 'antd';
import React, { useEffect } from 'react';
const { Option } = Select;
// 定义国家代码和扩展码的映射关系
const phoneExtensions: { [key: string]: string } = {
CA: '1',
CN: '86',
US: '1',
};
interface InternationalPhoneInputProps {
value?: { country?: string; phone?: string; extension?: string };
onChange?: (value: {
country: string;
phone: string;
extension?: string;
}) => void;
}
const InternationalPhoneInput: React.FC<InternationalPhoneInputProps> = ({
value = {},
onChange,
}) => {
const {
country = 'CA',
phone = '',
extension = phoneExtensions['CA'],
} = value || {};
useEffect(() => {
triggerChange({ extension });
}, []);
const triggerChange = (
changedValue: Partial<{
country: string;
phone: string;
extension?: string;
}>,
) => {
if (onChange) {
onChange({
country,
phone,
...value,
...changedValue,
});
}
};
const onCountryChange = (newCountry: string) => {
triggerChange({
country: newCountry,
extension: phoneExtensions[newCountry],
});
};
const onPhoneChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
triggerChange({ phone: e.target.value });
};
return (
<Input
addonBefore={
<Select
value={country}
onChange={onCountryChange}
style={{ width: 100 }}
>
<Option value="CA">🇨🇦 +1</Option>
<Option value="CN">🇨🇳 +86</Option>
<Option value="US">🇺🇸 +1</Option>
{/* 添加更多国家代码 */}
</Select>
}
value={phone}
onChange={onPhoneChange}
placeholder="请输入联系电话"
/>
);
};
export default InternationalPhoneInput;