提问人:Freaked Out 提问时间:10/3/2023 更新时间:10/3/2023 访问量:39
将上传的 jsx 文件保存在本地,然后在 React js 中显示该文件
Save an uploaded jsx file locally and then display that file in React js
问:
我的任务是构建一个组件,要求用户上传一个用 react 构建的游戏(尤其是 jsx)。游戏上传后,它应该保存在项目目录中,以便以后可以用于显示和玩游戏。我可以上传游戏,但我必须指导下一步该做什么,如果我应该将其转换为 json 或 blob 或其他什么。我在下面附上我完成的代码。请帮帮我
import React, { useState } from 'react';
export default function AddGame() {
const [game, setGame] = useState();
const [gameFile, setGameFile] = useState();
const [loaded, setLoaded] = useState(false);
const handleChange = (e) => {
e.preventDefault()
setGame({ ...game, [e.target.name]: e.target.value })
// console.log(game);
}
const handleFileChange = (e) => {
setGameFile([...e.target.files])
setLoaded(true);
console.log(e.target.files)
console.log(e.target.files[0].name)
}
const handleSubmit = (e) => {
e.preventDefault()
console.log(gameFile)
}
return (
<>
<div className="container mx-auto w-fit">
<div>
<h3 className="text-center text-white text-4xl my-4 font-semibold">New Game</h3>
<form onSubmit={handleSubmit} className="shadow p-8 my-4 bg-zinc-200 rounded-lg flex flex-col items-center lg:w-[50rem] w-[30rem]">
<div className="mb-4 mt-2 flex align-top w-full">
<label className="text-zinc-900 font-semibold inline-block w-48">Game Title: </label>
<textarea onChange={handleChange} rows="1" minLength="3" maxLength="30" className="shadow rounded p-2 text-zinc-900 resize-none w-full" name="gameTitle" placeholder="Write title here" />
</div>
<div className="mb-4 mt-2 flex align-top w-full">
<label className="text-zinc-900 font-semibold inline-block w-48">Game Description: </label>
<textarea onChange={handleChange} rows="5" minLength="10" maxLength="1024" className="shadow rounded p-2 text-zinc-900 resize-none w-full" name="gameDescription" placeholder="Write description here" />
</div>
<div className="mb-4 mt-2 flex align-top w-full">
<label className="text-zinc-900 font-semibold inline-block w-48">Add Game File: </label>
<input
type="file"
className="text-zinc-900 w-full"
accept=".jsx, .js"
multiple
name="gameFile"
onChange={handleFileChange} />
</div>
<button className="border-2 rounded-lg h-12 px-4 py-2 border-neutral-600 bg-neural-600/[.20] transition duration-200 hover:bg-neutral-600 hover:text-white text-zinc-900 disabled:pointer-events-none disabled:cursor-not-allowed">Submit</button>
</form>
</div >
</div >
</>
);
}
答: 暂无答案
评论