首页 > 解决方案 > 在头像 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>
  );
}

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

标签: javascriptreactjs

解决方案


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

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

推荐阅读