【问题标题】:Display an image in avatar React在头像 React 中显示图像
【发布时间】:2020-04-23 14:35:00
【问题描述】:

我想在头像中显示上传的图片,所以我写了这段代码:

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>
  );
}

但不幸的是,代码运行时并没有显示图像! 我试图找出我的错误在哪里,但我没有找到它。

【问题讨论】:

  • 什么是Avatar?是你的模特还是第三方?
  • 浏览器控制台中的任何错误?另外,当使用&lt;img id="avatar"/&gt; 时会发生什么?
  • 头像来自 Material ui 库
  • 浏览器控制台没有错误,我尝试使用&lt;img id=''avatar''/&gt; 仍然无法显示上传的图像
  • 您能否为此使用codesandbox.io 创建一个small demo 以显示正在发生的问题。然后我可以尝试进一步研究。

标签: javascript reactjs


【解决方案1】:

您好,我已经修复了您的代码。请检查一下。

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>
    );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2022-01-01
    • 2019-02-07
    • 2016-11-02
    • 2019-10-01
    • 2021-07-31
    相关资源
    最近更新 更多