【发布时间】:2021-02-02 01:25:13
【问题描述】:
由于某种原因,我的组件在第一次本地状态更改时会闪烁(例如,如果我切换复选框或聚焦并模糊输入字段),我无法找出导致问题的原因。
我在其他具有复选框/输入的页面上也遇到了这个问题。另外,我的 react-hook-form onChange 验证只有在我至少聚焦和模糊一次时才开始工作。
const MyAccount = ({ handleFormSubmit }) => {
const [isNoSmartphoneChecked, setNoSmartphoneChecked] = useState(false)
const [isPhoneNumberAnonymousChecked, setPhoneNumberAnonymousChecked] = useState(false)
const {
handleSubmit,
register,
errors,
control,
setValue,
clearErrors,
formState: { isSubmitting, touched },
} = useForm<FormData>({
defaultValues: {
phoneNumber: null,
noSmartphone: false,
phoneNumberAnonymous: false,
logoChanged: false,
},
mode: 'onChange',
})
const onSubmit = handleSubmit((values) => {
// handleFormSubmit(values)
})
const handleToggleNoSmartphoneCheckbox = () => {
setNoSmartphoneChecked(!isNoSmartphoneChecked)
setValue('noSmartphone', !isNoSmartphoneChecked)
clearErrors(['phoneNumber'])
}
const handleToggleAnonymousNumberCheckbox = () => {
setPhoneNumberAnonymousChecked(!isPhoneNumberAnonymousChecked)
setValue('phoneNumberAnonymous', !isPhoneNumberAnonymousChecked)
}
const isContinueButtonActive = (errors && !errors.phoneNumber && touched.phoneNumber) || isNoSmartphoneChecked
return (
<MyAccountWrapper>
<UserInfo>
<Form>
<FormItem hasError={errors && !!errors.phoneNumber && !isNoSmartphoneChecked}>
<Label>Your mobile phone number</Label>
<Controller
name="phoneNumber"
control={control}
rules={{ required: !isNoSmartphoneChecked }} //if noSmartphone isn't checked phone number required
as={<PhoneInput placeholder={''} autoFormat={false} />}
/>
</FormItem>
<FormItem>
<CustomCheckbox
isChecked={isNoSmartphoneChecked}
handleToggleCheckbox={handleToggleNoSmartphoneCheckbox}
label="I do not have a smartphone (that works) "
register={register}
name="noSmartphone"
/>
</FormItem>
<FormItem>
<CustomCheckbox
isChecked={isPhoneNumberAnonymousChecked}
handleToggleCheckbox={handleToggleAnonymousNumberCheckbox}
label="I do not want to share my phone with my employer"
register={register}
name="phoneNumberAnonymous"
/>
</FormItem>
</Form>
<ButtonWrapper>
{isContinueButtonActive && !isSubmitting ? <ActiveBtn onClick={onSubmit} /> : <DisabledBtn />}
</ButtonWrapper>
</UserInfo>
</MyAccountWrapper>
)
}
export default MyAccount
【问题讨论】:
-
您似乎遇到了字体问题。也许您可以确保在更改状态之前加载字体。
-
你在使用样式组件吗?在全局样式规则导致字体文件像这样重新加载之前,我经历过类似的事情。
-
就是这样。我现在知道这是
styled-componentsGlobalStyles的常见问题,谢谢,我会从这里解决
标签: reactjs react-hooks styled-components react-hook-form