我有一个有onSubmit的表单,在那个回调中我有一个uploady.showFileUpload(),但是uploady.showFileUpload()之后的代码被执行。
现在的问题是我如何等待上传,然后执行其余的代码?
const handleSubmit2 = useCallback((e)=> {
uploady.showFileUpload(); //(HERE SHOULD WAIT FOR IT TO FINISH FILE SELECT)
//OTHER CODE
});
这个codesandbox在使用Uploady与表单的情况下应该是有帮助的:https://codesandbox.io/s/react-uploady-inside-form-ys1wx
这个想法是在提交表单时单独显示文件选择提示符:
import React, { useState, useCallback, useMemo, forwardRef } from "react";
import Uploady, {
useUploadyContext
} from "@rpldy/uploady";
import { asUploadButton } from "@rpldy/upload-button";
const MyUploadField = asUploadButton(
forwardRef(({ onChange, ...props }, ref) => {
return (
<div {...props} ref={ref} id="form-upload-button" title={text}>
Select file
</div>
);
})
);
const MyForm = () => {
const [fields, setFields] = useState({});
const [fileName, setFileName] = useState(null);
const uploadyContext = useUploadyContext();
const onSubmit = useCallback(() => {
uploadyContext.processPending({ params: fields });
}, [fields, uploadyContext]);
const onFieldChange = useCallback(
(e) => {
setFields({
...fields,
[e.currentTarget.id]: e.currentTarget.value
});
},
[fields, setFields]
);
return (
<form>
<MyUploadField autoUpload={false} />
<input
onChange={onFieldChange}
id="field-name"
type="text"
placeholder="your name"
/>
<SubmitButton
id="form-submit"
type="button"
onClick={onSubmit}
>
Submit Form
</SubmitButton>
</form>
);
};
<Uploady
clearPendingOnAdd
destination={{ url: "[upload-url]" }}
multiple={false}
>
<MyForm />
</Uploady>
选择是通过使用asUploadButton HOC实现的。当然,您也可以像使用uploady.showFileUpload();
那样自己操作。
然后,提交按钮使用uploady的processPending方法开始上传。