Javascript 使用Formik和包装材料文本字段导致按键模糊
我不确定是什么改变了我的自定义Javascript 使用Formik和包装材料文本字段导致按键模糊,javascript,reactjs,material-ui,formik,onblur,Javascript,Reactjs,Material Ui,Formik,Onblur,我不确定是什么改变了我的自定义TextFields开始以这种方式运行,但我正在包装材料UITextFields以使用Formik验证。我已经包括了一个完整的代码沙盒,可以使用它进行分叉和播放 目前,当我键入(或在数字字段中单击上/下箭头)时,字段“模糊”,我必须每按一次键重新聚焦以继续键入。数值字段会导致数值下降而不是增加 这是我的自定义TextField包装: 从“React”导入React; 从“formik”导入{FieldAttributes,useField}; 进口{ InputBa
TextField
s开始以这种方式运行,但我正在包装材料UITextField
s以使用Formik验证。我已经包括了一个完整的代码沙盒,可以使用它进行分叉和播放
目前,当我键入(或在数字字段中单击上/下箭头)时,字段“模糊”,我必须每按一次键重新聚焦以继续键入。数值字段会导致数值下降而不是增加
这是我的自定义TextField
包装:
从“React”导入React;
从“formik”导入{FieldAttributes,useField};
进口{
InputBaseComponentProps,
TextField作为MuiTextField
}来自“@材料界面/核心”;
界面文本字段道具{
标签:字符串;
内联?:布尔值;
inputProps?:InputBaseComponentProps;
}
常量文本字段:React.FC=({
inline=false,
…道具
}) => {
常量{type,label,占位符,inputProps}=props;
const[field,meta]=useField(props);
常量errorText=meta.error&&meta.toucted?meta.error:;
常量字段=()=>(
);
内联返回(
) : (
);
};
导出默认文本字段;
下面是代码沙箱,以防我的示例代码与我的错误无关:
我认为每次输入文本或关注字段时,您都在重新创建
MuiTextField
在功能组件中重新渲染时,React将再次运行所有代码,因此字段()
将再次创建MuiTextField
要解决此问题,可以将字段
和文本字段
分为两个组件
const Field: React.FC<FieldAttributes<TextFieldProps>> = (props) => {
const { type, label, placeholder, inputProps } = props;
const [field, meta] = useField<TextFieldProps>(props);
const errorText = meta.error && meta.touched ? meta.error : "";
return (
<MuiTextField
{...field}
label={label}
variant="outlined"
margin="dense"
type={type}
placeholder={placeholder ? placeholder : label}
helperText={errorText}
error={!!errorText}
inputProps={inputProps}
/>
);
};
const TextField: React.FC<FieldAttributes<TextFieldProps>> = ({
inline = false,
...props
}) => {
return inline ? (
<Field {...props} />
) : (
<div>
<Field {...props} />
</div>
);
};
const字段:React.FC=(道具)=>{
常量{type,label,占位符,inputProps}=props;
const[field,meta]=useField(props);
常量errorText=meta.error&&meta.toucted?meta.error:;
返回(
);
};
常量文本字段:React.FC=({
inline=false,
…道具
}) => {
内联返回(
) : (
);
};
以下是代码沙盒:
找到一篇文章供您阅读:我感觉添加
字段
会引起问题。我以前也这样做过,也有类似的行为。我的回答能帮助你吗?如果没有,请为我们提供更多详细信息。@Micfong,您的回答非常有效!我今天只需要留出时间来解决这个问题。