我正在为我的输入组件使用 react-hook-form,但有一个问题。在一些文本字段中,例如,用于验证的文本字段只需要数字,我不知道该怎么做,对于正常的 textInput
,我们可以使用正则表达式,比如
const [numberInput, setNumberInput] = useState("")
function onTextChanged(value) {
setNumberInput(value.replace(/[^0-9]/, ""))
}
并将该函数和挂钩值分别放在 onTextChange
和 value
上,我在react-hook-form上尝试了上面的相同方法,但它不起作用!我仍然可以输入其他字符,如“+”或“-”,当然是使用数字键盘
所以这是 TextField 组件
export interface HTextFieldProps extends TextFieldProps {
control: Control<any>
name: string
defaultValue?: string
}
/**
* Describe your component here
*/
export const HTextField = function HookformTextField(props: HTextFieldProps) {
const { name, control, defaultValue = "", ...restProps } = props
return (
<Controller
control={control}
name={name}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<TextField
{...restProps}
onChangeText={onChange}
value={value}
defaultValue={defaultValue}
error={(error && error.message) as TxKeyPath}
/>
)}
defaultValue={defaultValue}
/>
)
}
这是我使用它的时候
<HTextField
onChangeText={(value) => onTextChanged(value)}
value={numberInput}
name={"times"}
control={control}
autoCapitalize="none"
keyboardType={Platform.OS === "android" ? "numeric" : "number-pad"}
returnKeyType="done"
inputStyle={INPUT_STYLE}
required
/>
那么我怎样才能在 react-hook-form 中只使用数字,看起来像这样,非常感谢
原文由 CODEforDREAM 发布,翻译遵循 CC BY-SA 4.0 许可协议
仅整数的解决方案
您可以将
<TextField />
proptype
设置为number
然后将只允许数字。前导零或指数的解决方案
正如这里的评论中所指出的,一个版本通过使用 RHF 的验证功能也接受前导零或指数符号。