gpt4 book ai didi

reactjs - 如何在 react-dropzone 中的提交按钮上调用 axios?

转载 作者:行者123 更新时间:2023-12-04 11:36:47 26 4
gpt4 key购买 nike

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

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

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

最佳答案

我已经做了:

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

关于reactjs - 如何在 react-dropzone 中的提交按钮上调用 axios?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57237983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com