繁体   English   中英

如何在反应中从功能组件访问文件

[英]How to access file from functional component in react

我试图从表单访问文件,但它不会获取它的数据。 我怎样才能在反应功能组件中做到这一点。 我希望有人可以帮助我解决这个问题,谢谢。 我尝试过使用事件,但那是 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;

您正在错误地处理文件输入。 尝试像这样更改输入:

  <input
       type="file"
       value={file}
       onChange={(e) => getFile(e.target.files[0])}
    />

此外,将文件 useState 初始化更改为:

  const [file, getFile] = useState(null);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM