我是刚开始编程和学习的。我目前要做的是创建一个表单字段,如下所示,该字段可以在单击按钮时上传文件。

一旦文件上传并提交给api之前,应该会看到表单字段中的文件名,如下所示

我尝试了如下所示,但这只显示浏览文件按钮,但不使用添加文件占位符的输入字段。
<input
type="file"
id={`${fieldRoot}.file`}
ref={fileInput}
style={{ display: 'none' }}
accept=".pem"
onChange={() => {
/*do something*/
console.log('hello')
}}
/>
<Button
minWidth="126px"
//onClick={handleUploadClick}
>
Browse file
</Button>有人能帮我做这个吗。谢谢。
发布于 2022-02-23 09:31:56
<input type="file"/>也是一个输入。因此,您可以使用<label>标记,并将其样式设置为按钮。在这种情况下,我使用图像代替。hidden属性使实际的<input />不可见。 <input
type="file"
id="avatar"
onChange={fileSelectedHandler}
hidden
/>
<label className={profileStyle.uploadLabel} htmlFor="avatar">
<Image
width="25px"
height="25px"
src="/icons/upload-image-icon.jpeg"
alt="upload-avatar"
/>
</label>这是你想要的:
import React, { useState } from "react";
export const Upload = () => {
const [filename, setFilename] = useState("");
return (
<>
<input
value={filename}
type="text"
style={{
width: 200,
height: 28,
padding: 0,
border: "1px solid #767676"
}}
/>
<input
type="file"
id="upload"
hidden
onChange={(e) => {
// You have your file detail in e.tartget.files
console.log(e.target.files[0]);
setFilename(e.target.files[0].name);
}}
/>
<label
htmlFor="upload"
style={{
width: 90,
background: "#767676",
color: "#fff",
padding: 5
}}
>
Browse
</label>
</>
);
};检查这个演示
https://stackoverflow.com/questions/71234272
复制相似问题