我在应用程序中使用Formik
进行表单制作。当我将表单发送到本地服务器时,将创建带有标题的图像。附加我应该使用input type="file"
的图像。但是我对使用formik的经验很少。
input type="file"
?现在,我想创建附加类似于InputTitle.js的图像组件InputImage.js的输入。
const AddImage = (props) => {
const {handleSubmit, values, handleChange} = useFormik({
initialValues: {
title: '',
image: '' // Did I write correctly here?
},
validateOnchange: false,
onSubmit: async (formValues) => {
const response = await api(`${imageRoutePath}`, {
method:'POST',
body: JSON.stringify(formValues),
});},
});
return (
<div>
<form onSubmit={handleSubmit}>
<InputTitle
label="title"
id="title"
inputProps={{
name:'title',
value: values.title,
onChange: handleChange,
}}
/>
<InputImage
label="image"
id="image"
inputProps={{
name:'image',
// WHAT I SHOULD WRITE THERE?
onChange: handleChange,
}}
/>
<button type="submit" disabled={isSubmitting}>Add</button>
</form>
</div>
);
};
export default AddImage;
const InputImage = ({
label, inputProps, error, id,
}) => (
<div className="formInputCategory">
<label htmlFor={id} className="formInputLabelCategory">
{label}
</label>
<input {...inputProps} id={id} />
{error && <span className="formInputErrorCategory">{error}</span>}
</div>
);
InputImage.propTypes = {
label: PropTypes.string.isRequired,
// WHAT I SHOULD WRITE THERE?
error: PropTypes.string,
id: PropTypes.string.isRequired,
};
InputImage.defaultProps = {
error: '',
}
const InputTitle = ({
label, inputProps, error, id,
}) => (
<div className="formInputCategory">
<label htmlFor={id} className="formInputLabelCategory">
{label}
</label>
<input {...inputProps} id={id} />
{error && <span className="formInputErrorCategory">{error}</span>}
</div>
);
InputTitle.propTypes = {
label: PropTypes.string.isRequired,
inputProps: PropTypes.instanceOf(Object).isRequired,
error: PropTypes.string,
id: PropTypes.string.isRequired,
};
InputTitle.defaultProps = {
error: '',
}
答案 0 :(得分:0)
Formik默认情况下不支持文件上传,但是您可以尝试以下操作
<input id="file" name="file" type="file" onChange={(event) => {
setFieldValue("file", event.currentTarget.files[0]);
}} />
“文件”代表您用于保存文件的密钥
setFieldValue是从<Formik />
您的代码如下:
const AddImage = (props) => {
const {handleSubmit, values, handleChange, setFieldValue } = useFormik({
initialValues: {
title: '',
image: '' // Did I write correctly here?
},
validateOnchange: false,
onSubmit: async (formValues) => {
const response = await api(`${imageRoutePath}`, {
method:'POST',
body: JSON.stringify(formValues),
});},
});
return (
<div>
<form onSubmit={handleSubmit}>
<InputTitle
label="title"
id="title"
inputProps={{
name:'title',
value: values.title,
onChange: handleChange,
}}
/>
<InputImage
label="image"
id="image"
inputProps={{
name:'file',
id="file",
// WHAT I SHOULD WRITE THERE?
type="file",
onChange={(event) => {
setFieldValue("file", event.currentTarget.files[0]);
}},
}}
/>
<button type="submit" disabled={isSubmitting}>Add</button>
</form>
</div>
);
};
export default AddImage;