javascript - 在头像 React 中显示图像
问题描述
我想在头像中显示上传的图像,所以我写了这段代码:
export default function App() {
const handleChange = function loadFile(event){
document.getElementById("avatar").src = URL.createObjectURL(event.target.files[0]);
}
return (
<div className="App">
<input type="file" onChange={handleChange} id="upload" accept="image/*" style={{display:"none"}}/>
<label htmlFor="upload">
<IconButton color="primary" aria-label="upload picture" component="span">
<Avatar id="avatar" src="/*photo URL using GetEvent */"
style={{
width: "60px",
height: "60px",
}}
/>
</IconButton>
</label>
<label fro="avatar"></label>
</div>
);
}
但不幸的是,代码运行并且不显示图像!我试图找出我的错误在哪里,但我没有找到它。
解决方案
你好,我已经修复了你的代码。请检查一下。
export default function App() {
const [file, setFile] = useState(null);
const handleChange = function loadFile(event) {
if (event.target.files.length > 0) {
const file = URL.createObjectURL(event.target.files[0]);
setFile(file);
}
};
return (
<div className="App">
<input type="file" onChange={handleChange} id="upload" accept="image/*" style={{display: "none"}}/>
<label htmlFor="upload">
<IconButton color="primary" aria-label="upload picture" component="span">
<Avatar id="avatar" src={file}
style={{
width: "60px",
height: "60px",
}}
/>
</IconButton>
</label>
<label htmlFor="avatar"/>
</div>
);
}
推荐阅读
- c++ - 您的一个应用程序进程的 MPI 错误终止,被信号 9 杀死
- html - 在逻辑应用上使用从共享邮箱发送电子邮件 (V2) 发送 HTML 电子邮件
- android - assets_audio_player 不能使用 realtimePlayingInfos.current.audio.audio.metas.image.path
- postgresql - postgres 函数看不到变量
- python - 从拟合的 xgboost 模型对象中检索超参数
- javascript - 跳过图表 js 中没有值的日期
- python - 让用户选择要重新采样的时间范围
- python - Plotly/Jupyter 中的 LaTeX 无法在 Firefox 上运行
- postgresql - 如果需要,使用 pg_ctl 启动 Postgres DB
- db2 - IBM CDC 表应该已经被刷新。转换服务器将终止