Reactjs 无法在React中上载图像
我试图使用React的useState来保存图像,然后上传,但它不起作用。我正在做下一步。Reactjs 无法在React中上载图像,reactjs,typescript,Reactjs,Typescript,我试图使用React的useState来保存图像,然后上传,但它不起作用。我正在做下一步。 我们如何解决这个问题谢谢您的合作 首先,我们通过[img,setImg]=useState(null)设置初始值 然后通过setImg将所选图像文件从输入标签存储到img 最后,我们通过addEvent函数将图像反映到数据库中 问题: 图像文件不会反映在数据库中 我尝试在addEvent中输出console.log,但它返回了null 代码如下: import React, { useState }
我们如何解决这个问题谢谢您的合作强>
[img,setImg]=useState(null)设置初始值代码>
setImg
将所选图像文件从输入标签存储到img
addEvent
函数将图像反映到数据库中- 图像文件不会反映在数据库中
- 我尝试在
中输出addEvent
,但它返回了console.log
null
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch } from "../../app/store";
import { TextField, Button, IconButton } from "@material-ui/core";
import styles from "./NewEvent.module.css";
import {
fetchAsyncGetEvents,
fetchAsyncNewEvent,
fetchPostEnd,
fetchPostStart,
resetOpenNewEvent,
} from "./eventSlice";
import { File } from "../types";
import { MdAddAPhoto } from "react-icons/md";
const NewEvent: React.FC = () => {
const dispatch: AppDispatch = useDispatch();
const [title, setTitle] = useState("");
const [img, setImg] = useState<File | null>(null);
const addEvent = async (e: React.MouseEvent<HTMLElement>) => {
e.preventDefault();
const packet = {
title: title,
img: img,
};
await dispatch(fetchPostStart());
await dispatch(fetchAsyncNewEvent(packet));
await dispatch(fetchPostEnd());
await dispatch(resetOpenNewEvent());
};
const handlerEditPicture = () => {
const fileInput = document.getElementById("imgInput");
fileInput?.click();
};
return (
<>
<form className={styles.newEvent_signUp}>
<h2 className={styles.newEvent_title}>種目追加</h2>
<br />
<TextField
placeholder="ベンチプレス?"
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<input
type="file"
id="imgInput"
hidden={true}
onChange={(e) => setImg(e.target.files![0])}
/>
<br />
<IconButton onClick={handlerEditPicture}>
<MdAddAPhoto />
</IconButton>
<br />
<Button
disabled={!title}
variant="contained"
color="primary"
type="submit"
onClick={addEvent}
>
新規追加
</Button>
</form>
</>
);
};
export default NewEvent;
import React,{useState}来自“React”;
从“react-redux”导入{useSelector,useDispatch};
从“../../app/store”导入{AppDispatch}”;
从“@material ui/core”导入{TextField,Button,IconButton};
从“/NewEvent.module.css”导入样式;
进口{
fetchAsyncGetEvents,
fetchAsyncNewEvent,
回执,
获取启动后,
重置OpenNewEvent,
}来自“/eventSlice”;
从“./types”导入{File};
从“react icons/md”导入{MdAddAPhoto};
const NewEvent:React.FC=()=>{
const dispatch:AppDispatch=usedpatch();
const[title,setTitle]=useState(“”);
const[img,setImg]=useState(null);
const addEvent=async(e:React.MouseEvent)=>{
e、 预防默认值();
常量数据包={
标题:标题,,
img:img,
};
等待分派(fetchPostStart());
等待调度(fetchAsyncNewEvent(数据包));
等待分派(fetchPostEnd());
等待调度(resetOpenNewEvent());
};
常量handlerEditPicture=()=>{
const fileInput=document.getElementById(“imgInput”);
fileInput?。单击();
};
返回(
種目追加
setTitle(e.target.value)}
/>
setImg(例如target.files![0])}
/>
新規追加
);
};
导出默认NewEvent;