[英]how can i set React initialState for image files
i'm making form component for registering certain contents information but as you see, i have problem with ts issue.我正在制作用于注册某些内容信息的表单组件,但如您所见,我遇到了 ts 问题。
function handleCategoryFormData
is handling input value. function
handleCategoryFormData
正在处理输入值。 but when i set image files in image
state, // TS2418: Type of computed property's value is 'File', which is not assignable to type 'string'.
但是当我在
image
state 中设置图像文件时, // TS2418: Type of computed property's value is 'File', which is not assignable to type 'string'.
is showing.正在显示。 so i changed
image
initialState.所以我改变了
image
初始状态。 but it's not working.但它不工作。 how can i handle this problem?
我该如何处理这个问题?
import React, { useState } from "react";
import _ from "lodash";
import { Button, FormLayout, Input, PageTitle } from "@components/common";
const CategoryFormPage = () => {
const [categoryFormData, setCategoryFormData] = useState({
image: "",
name: "",
order: "",
searchingTag: "",
exceptionTag: "",
previousCategory: [],
connectedInterest: [],
});
const handleCategoryFormData = (e: React.ChangeEvent) => {
const { name, value, files } = e.target as HTMLInputElement;
if (name === "image" && files) {
const imageFile = _.get(files, 0);
// TS2418: Type of computed property's value is 'File', which is not assignable to type 'string'.
// TS2418: Type of computed property's value is 'File', which is not assignable to type 'null'.
// TS2418: Type of computed property's value is 'File', which is not assignable to type 'undefined'.
setCategoryFormData({ ...categoryFormData, [name]: imageFile }); // [![enter image description here][1]][1]<= error happend
return;
}
setCategoryFormData({ ...categoryFormData, [name]: value });
};
return (
<div>
...
</div>
);
};
export default CategoryFormPage;
[1]: https://i.stack.imgur.com/tfgAK.png
Try this!尝试这个! what you are doing is assigning
File
type to a string you need to explicitly define the type that the image would accept string | File
您正在做的是将
File
类型分配给一个字符串,您需要明确定义图像将接受的类型string | File
string | File
for type. string | File
类型。
{...}
type categoryFormDataType = {
image: string | File;
name: string;
order: string;
searchingTag: string;
exceptionTag: string;
previousCategory: string[]; // define array here as well assuming it would be array of string
connectedInterest: string[]; // define array here as well assuming it would be array of string
};
const CategoryFormPage = () => {
const [categoryFormData, setCategoryFormData] = React.useState<categoryFormDataType>({
image: '',
name: '',
order: '',
searchingTag: '',
exceptionTag: '',
previousCategory: [],
connectedInterest: [],
});
{...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.