我的目标是在头像中显示一个图像,如果我可以在头像图标上选择一个图像文件,那么它应该在头像中显示图像。但我无法做到这一点。
有没有人能帮我在头像里显示图像?
发布于 2020-07-29 20:27:09
你应该这样做:
onImageChange = event => {
let file = URL.createObjectURL(event.target.files[0]);
console.log("File", file);
if (file === undefined) {
console.log("File removed");
} else {
this.setState({
image: file
});
}};
和渲染
<Avatar src={this.state.image || '/static/images/avatar/1.jpg'} width="250" height="250" />不要忘记在卸载时撤消
componentWillUnmount() {
URL.revokeObjectURL(this.state.image);
}发布于 2020-07-29 20:24:29
请使用保存到状态的图像。如下所示
<Avatar src={this.state.image} width="250" height="250" />在构造函数中,使用默认值加载它。
constructor(props) {
super(props);
this.state = {
'image': '/static/images/avatar/1.jpg'
};
}并且图像更改事件应该是
onImageChange = event => {
let file = URL.createObjectURL(event.target.files[0]);
console.log("File", file);
if (file == undefined) {
console.log("File removed");
} else {
this.setState({
image: file
});
}
};https://stackoverflow.com/questions/63153450
复制相似问题