我正在使用Next.js 14上react-phone-number-input中的PhoneInputWithCountry组件。我想在用户单击复选框时在PhoneInputWithCountry组件上设置值。所以我将值设置为'defaultValue'和'Value'属性,但它不起作用。你能帮我设置值吗?
export default function Home() {
const { control } = useForm();
const [tel, setTel] = useState("");
const specialTel = "+1 604 111 1111";
// fill tel value * it doesn't set
const fillValue = (isChecked: boolean) => {
if (isChecked == true) {
setTel(specialTel);
} else {
console.log("false");
}
};
return (
<>
<div className="w-[150px]" style={{ width: "150px" }}>
<label htmlFor="specialTel">Set Special Tel</label>
<input
id="specialTel"
type="checkbox"
onChange={(event) => fillValue(event.target.checked)}
/>
<PhoneInputWithCountry
name="tel"
value={tel}
defaultValue={tel}
control={control}
countries={["CA"]}
addInternationalOption={false}
defaultCountry="CA"
min={10}
international={true}
limitMaxLength={true}
onChange={(val: string) => {
console.log(val);
setTel(val);
}}
/>
</div>
</>
);
}
字符串
CodeSandBox
1条答案
按热度按时间5fjcxozz1#
我找到了解决方案。基于以下情况,当我想在渲染后设置值时,我不能使用PhoneInputWithCountry。因为它不接受'value'属性。https://gitlab.com/catamphetamine/react-phone-number-input/-/issues/72
所以,我必须使用其他组件(例如PhoneInputWithCountrySelect)。关于我的代码,只需要导入'PhoneInputWithCountrySelect'并将PhoneInputWithCountrySelect更改为PhoneInputWithCountrySelect,然后它就可以工作了。
字符串