只有当我把我的图像src
改成AddProjects
时它才起作用,而不是当它是AddProjects.Img
时,这是我想要的。
我如何告诉React URL应该保存在AddProjects.Img
中?下面是我的代码:
export default function AddProjects() {
const [AddProjects, setAddProjects] = useState({
name: "",
Discription: "",
git: "",
Img: "",
});
// const [imgAdd,setImgAdd] = useState()
const inputFile = useRef(null);
function handleChange(e) {
const { name, value } = e.target;
setAddProjects((newProjects) => ({
...newProjects,
[name]: value,
}));
}
function imgChange(e) {
console.log(e.target.files);
setAddProjects(URL.createObjectURL(e.target.files[0]));
}
console.log(AddProjects);
return (
<div className="AddProjects">
<form>
<h2>Add New Project</h2>
<input
type="text"
placeholder="Project Name..."
value={AddProjects.name}
name="name"
onChange={handleChange}
/>
<input
type="text"
placeholder="Project Discription..."
value={AddProjects.Discription}
name="Discription"
onChange={handleChange}
/>
<input
type="text"
placeholder="Git Repository/Code..."
value={AddProjects.git}
name="git"
onChange={handleChange}
/>
<input
type="file"
accept="image/jpg,image/jpeg"
name="Img"
onChange={imgChange}
ref={inputFile}
/>
<button type="button" onClick={() => inputFile.current.click()}>
Add New Image
</button>
<button type="submit">Submit Project</button>
</form>
<img src={AddProjects.Img} alt="" />
</div>
);
}
1条答案
按热度按时间ohtdti5x1#
imgChange
函数就是这里的问题所在,因为你已经用图像URL替换了你的对象状态。