[英]How to access file from functional component in react
Im trying to access the file from the form but it wont get the data for it.我试图从表单访问文件,但它不会获取它的数据。 How can I do this in a react functional component.
我怎样才能在反应功能组件中做到这一点。 I hope someone can help me with this, Thanks.
我希望有人可以帮助我解决这个问题,谢谢。 I have tried using event but that is null and I cant find how to do this in a functional component so I dont understand why this wont work.
我尝试过使用事件,但那是 null 并且我找不到如何在功能组件中执行此操作,所以我不明白为什么这不起作用。
import React, { useState } from "react";
import {
Grid,
Paper,
Avatar,
TextField,
Button,
Typography,
Link,
Input,
} from "@material-ui/core";
import UserIcon from "@material-ui/icons/AccountBox";
import axios from "axios";
const Register = () => {
const [username, getUsername] = useState("");
const [password, getPassword] = useState("");
const [email, getEmail] = useState("");
const [file, getFile] = useState([]);
const registerUser = () => {
const data = new FormData();
data.append("file", file);
data.append("userName", username);
data.append("password", password);
data.append("email", email);
axios
.post("http://localhost:9020/api/v1/user/register", data)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
};
const paperStyle = {
padding: 20,
height: "70vh",
width: 280,
margin: "20px auto",
};
const avatarStyle = { backgroundColor: "#1bbd7e" };
const btnstyle = { margin: "8px 0" };
return (
<Grid>
<Paper elevation={10} style={paperStyle}>
<Grid align="center">
<Avatar style={avatarStyle}>
<UserIcon />
</Avatar>
<h2>Register for an account</h2>
</Grid>
<TextField
label="Username"
placeholder="Enter username"
fullWidth
required
onChange={() => getUsername()}
/>
<TextField
label="Password"
placeholder="Enter password"
type="password"
fullWidth
required
onChange={() => getPassword()}
/>
<TextField
label="Email"
placeholder="Enter Email"
type="text"
fullWidth
required
onChange={() => getEmail()}
/>
<Input type="file" required onChange={() => getFile()} />
<Button
type="submit"
color="primary"
variant="contained"
style={btnstyle}
fullWidth
onClick={() => registerUser()}
>
Sign Up
</Button>
<Typography>
{" "}
Already have an account<Link href="#"> Sign In</Link>
</Typography>
</Paper>
</Grid>
);
};
export default Register;
You are handling the file input incorrectly.您正在错误地处理文件输入。 Try changing the input like this:
尝试像这样更改输入:
<input
type="file"
value={file}
onChange={(e) => getFile(e.target.files[0])}
/>
Also, Change the file useState initialisation as:此外,将文件 useState 初始化更改为:
const [file, getFile] = useState(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.