javascript - Typescript React.Js 文件上传事件 Ts2322 错误

标签 javascript reactjs typescript

您好,我对 React.js 和 typescript 非常陌生。我正在尝试上传一个简单的文件以及简单的输入。

我检查了一些与网络上文件上传或输入元素事件相关的示例( ex1ex2ex3 ),但我无法使它们中的任何一个工作。

这是我的 tsx 文件。

import * as React from 'react';
//import * as $ from "jquery";
import { RouteComponentProps } from 'react-router';
import { Button, Form, FormGroup, Label, Input, FormText } from 'reactstrap';
interface UploadContainerState {

    tcknVkn: number;
    proclamationYear: number;
    file: FileList|null;
}
export default class UploadContainer extends React.Component<{}, UploadContainerState> {
    constructor(props: any) {
        super(props);
        this.state = {
            proclamationYear: 0,
            tcknVkn: 0,
            file: null
        }
        this.proclamationYearChange = this.proclamationYearChange.bind(this);
        this.tcknVknChange = this.tcknVknChange.bind(this);
        this.uploadFile = this.uploadFile.bind(this);
        this.fileChange = this.fileChange.bind(this);

    }
    proclamationYearChange(event: any) {
        this.setState({ proclamationYear: event.target.value });
    }
    tcknVknChange(event: any) {
        this.setState({ tcknVkn: event.target.value });
    }
    fileChange(event: any) {
        this.setState({ file: event.target.files[0] });
    }

    render() {
        return (
            <div>

                <form className="uploader" encType="multipart/form-data" >
                    <br />
                    <FormGroup>
                        <Label for="proclamationYear">Beyanname Yılı</Label>
                        <Input type="text" name="proclamationYear" id="proclamationYear" placeholder="Beyanname Yılını Giriniz." onChange={this.proclamationYearChange} value={this.state.proclamationYear} />
                    </FormGroup>
                    <FormGroup>
                        <Label for="tcknVkn">Tckn/Vkn</Label>
                        <Input type="text" name="tcknVkn" id="tcknVkn" placeholder="Tckn/Vkn Giriniz." onChange={this.tcknVknChange} value={this.state.tcknVkn} />
                    </FormGroup>

                    <input  type="file" name="file" className="upload-file" onChange={this.fileChange} value={this.state.file} />
                    <input type="button"  value="Beyanname Yükle" onClick={this.uploadFile} />
                </form>
            </div>
        );
    }
    uploadFile(event: any) {
        event.preventDefault();
        let formData = new FormData();
        formData.append('file', event.target.myimage.files[0]);
        formData.append('tcknVkn', event.target.tcknVkn.value);
        formData.append('proclamationYear', event.target.proclamationYear.value);
        fetch('ProposalData/UploadFile', {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Content-Type': 'multipart/form-data',
                'Accept': 'application/json'
            },
            body: formData
        })
    }
};

我收到以下错误。

ERROR in [at-loader] ./ClientApp/components/UploadContainer.tsx:50:29 
    TS2322: Type '{ type: "file"; name: "file"; className: "upload-file"; onChange: (event: any) => void; value: Fi...' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.
  Type '{ type: "file"; name: "file"; className: "upload-file"; onChange: (event: any) => void; value: Fi...' is not assignable to type 'InputHTMLAttributes<HTMLInputElement>'.
    Types of property 'value' are incompatible.
      Type 'FileList | null' is not assignable to type 'string | number | string[] | undefined'.
        Type 'null' is not assignable to type 'string | number | string[] | undefined'.

这是我的 typescript 版本 5.6.0

我不明白这么简单的任务怎么会变成一场噩梦。

最佳答案

我知道这不是最佳解决方案。但这里为那些尝试使用 .net core、react.js 和 typescript 完成相同任务的人提供了完整的后端和前端代码。

这是我的 tsx 文件注释,我在界面中注释了文件属性并将其设为公共(public)属性(property)。

import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import { Button, Form, FormGroup, Label, Input, FormText } from 'reactstrap';
import ListGroup from 'reactstrap/lib/ListGroup';

interface UploadContainerState {

    tcknVkn: number;
    proclamationYear: number;
    alertVisible: boolean;

    //file: FileList
}
export default class UploadContainer extends React.Component<{}, UploadContainerState> {
    public file: File;
    constructor(props: any) {
        super(props);
        this.state = {
            proclamationYear: 0,
            tcknVkn: 0,
            alertVisible: false
        }
        this.proclamationYearChange = this.proclamationYearChange.bind(this);
        this.tcknVknChange = this.tcknVknChange.bind(this);
        this.uploadFile = this.uploadFile.bind(this);
        this.fileChange = this.fileChange.bind(this);

    }
    proclamationYearChange(event: any) {
        this.setState({ proclamationYear: event.target.value });
    }
    tcknVknChange(event: any) {
        this.setState({ tcknVkn: event.target.value });
    }
    onDismiss() {
        this.setState({ alertVisible: false });
    }

    fileChange(event: any) {
        this.file = event.target.files[0];
        event.preventDefault();

    }

    render() {
        return (
            <div>

                <form onSubmit={this.uploadFile} className="uploader" encType="multipart/form-data" >
                    <FormGroup>
                        <Label for="proclamationYear">Year</Label>
                        <Input type="text" name="proclamationYear" id="proclamationYear"  onChange={this.proclamationYearChange} value={this.state.proclamationYear} />
                    </FormGroup>
                    <FormGroup>
                        <Label for="tcknVkn">Tckn/Vkn</Label>
                        <Input type="text" name="tcknVkn" id="tcknVkn"  onChange={this.tcknVknChange} value={this.state.tcknVkn} />
                    </FormGroup>

                    <input type="file" name="file" accept=".pdf" className="upload-file" onChange={this.fileChange} />
                    <input type="submit" value="Submit" />
                </form>
            </div>
        );
    }
    uploadFile(event: any) {
        let that = this;
        event.preventDefault();
        let formData = new FormData();
        formData.append('file', this.file);
        formData.append('tcknVkn', event.target.tcknVkn.value);
        formData.append('proclamationYear', event.target.proclamationYear.value);
        fetch("ProposalData/UploadFile", {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Accept': 'application/json, */*',
            },
            body: formData
        })
            .then(handleErrors)
            .then(function (response) {
                console.log("ok");
            }).catch(function (error) {

                console.log(error);
            });
    }
};
function handleErrors(response: any) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

这是我的 Controller

public class FileUploadModel
{
    public string ProclamationYear { get; set; }
    public string TcknVkn { get; set; }
    public IFormFile File { get; set; }
}
 [HttpPost]
        public async Task<IActionResult> UploadFile([FromForm]FileUploadModel vm)
        {
            var file = vm.File;

关于javascript - Typescript React.Js 文件上传事件 Ts2322 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50641491/

相关文章:

javascript - 如果父元素只有 2 个子元素,则执行某些操作,否则执行其他操作

javascript - 如何通过xhrPost()发送csv文件?

javascript - 在 React 中上传之前获取图像预览

node.js - 使用 --module 选项在 Sublime Text 中使用 Typescript 构建系统配置

angular - 输入 'Observable<{} is not assignable to type ' Observable<HttpEvent<any>>'

javascript - Webpack 加载器测试是否运行多次?

javascript - 我遇到意外的 token 错误。它从哪里来?

reactjs - FCM 网络推送通知 Google Analytics

javascript - Angular/形式整数验证器

javascript - 如何停止用鼠标滚动时相对放置的元素的抖动?