具有react钩子形式和react输入掩码的矩阵UI不起作用



此代码不起作用,正在尝试多个版本,有人能帮忙吗?它会产生一个从可控到不可控的错误,加上口罩根本不起作用,我错过了什么?

https://github.com/react-hook-form/react-hook-form/issues/1255

这是一个代码沙盒:https://codesandbox.io/s/sad-shamir-nnh0c?fontsize=14&隐藏导航=1&主题=深色

import React, { useState } from 'react'
import { TextField } from '@material-ui/core'
import InputMask from 'react-input-mask'
import { useFormContext, Controller} from 'react-hook-form'
const PhoneInputMask = (props) => {
const { inputRef, ...other } = props;
return (
<InputMask
{...other}
mask={['(' , '+', /[3]/, /[5-8]/, /[1-9]/, ')', ' ', /d/, /d/, /d/, '-', /d/, /d/, /d/, /d/, /d/, /d/, /d/]}
inputRef={inputRef}
alwaysShowMask={true}
/>
)
}

const PhoneInput = (props) => {
const [textMask, setTextMask] = useState()
const handleChange = (event) => setTextMask(event.target.value)
const { errors, register, control } = useFormContext()
const { name, label, registerContext } = props
return (
<Controller
name={name}
control={control}
defaultValue=""
render={props => (
<TextField
margin="normal"
InputProps={{
inputComponent: PhoneInputMask,
value:textMask,
onChange: handleChange,
}}
name={name}
id={name}
inputRef={register(registerContext)}
label={label}
error={!!errors[name]}
helperText={(errors[name]) ? errors[name].message : null}
/>)}
/>
)
}
export default PhoneInput
<Controller
name="phone"
control={control}
defaultValue=""
render={({ field: { onChange, value } }) => (
<InputMask mask="+999999999999" value={value} onChange={onChange}>
{
inputProps => (
<TextField
error={!!errors.phone?.message}
label="Phone"
variant="outlined"
type="text"
fullWidth
required
{...inputProps}
/>
)
}
</InputMask>
)}
/>

对于从受控值变为非受控值的错误,需要添加defaultValue=""

最新更新