5

用户单击提交按钮时如何调用 axios?

无法在提交按钮上添加 onclick 事件处理程序,我应该在哪里声明调用 axios 或接受此代码中的 acceptedFiles 变量的 onClick 事件函数。

当用户删除文件时调用 useCallback,当用户删除文件时文件会自动上传。我希望在用户单击提交按钮时上传文件。

import React, {useCallback, Component} from 'react';
import {useDropzone} from 'react-dropzone';
import axios from 'axios';


function Basic(props) {

const onDrop = useCallback(acceptedFiles => {
    let formData = new FormData();

    for (var i = 0; i < acceptedFiles.length; i++) {
        let file = acceptedFiles[i];
        formData.append('articleFiles[]', file);
    }  

    axios({
      method: 'post',

      data: formData,
      )}


}, [])
const {acceptedFiles, getRootProps, getInputProps} = useDropzone({onDrop});


const files = acceptedFiles.map(file => (
    <li key={file.path}>
        {file.path}
        - {file.size}
        bytes
    </li>
));



return (
    <section className="container">
        <div {...getRootProps({className: 'dropzone'})}>
            <input {...getInputProps()}/>
            <p>Drag 'n' drop some files here, or click to select files</p>
        </div>
        {files.length > 0 && <React.Fragment>
            <div>
                <h4>Files</h4>
                <ul>{files}</ul>
            </div>
            <button>Submit</button> //<---
        </React.Fragment>}

    </section>
);
}

 export class UploadManuscript extends Component {

render() {


    return (<Basic/>)
}
}

export default UploadManuscript
4

1 回答 1

2

我已经做了:

import React, {Component} from 'react';
import {useDropzone} from 'react-dropzone';
import axios from 'axios'

function Basic(props) {

    const uploadFiles = () => {
        let formData = new FormData();

        for (var i = 0; i < acceptedFiles.length; i++) {
            let file = acceptedFiles[i];
            formData.append('articleFiles[]', file);
        }
       
       
        axios({
            method: 'post',
            
            data: formData,

            })
            

    }
    const {acceptedFiles, getRootProps, getInputProps} = useDropzone();

    console.log(props.id)

    const files = acceptedFiles.map(file => (
        <li key={file.path}>
            {file.path}
            - {file.size}
            bytes
        </li>
    ));

   

    return (
        <section className="container">
            <div {...getRootProps({className: 'dropzone'})}>
                <input {...getInputProps()}/>
                <p>Drag 'n' drop some files here, or click to select files</p>
            </div>
            {files.length > 0 && <React.Fragment>
                <div>
                    <h4>Files</h4>
                    <ul>{files}</ul>
                </div>
                <button onClick={uploadFiles}>Submit</button>
            </React.Fragment>}

        </section>
    );
}

export class UploadManuscript extends Component {

    render() {
      

        return (<Basic/>)
    }
}

export default UploadManuscript

于 2019-07-28T04:50:21.533 回答