所以我正在创建让用户上传少量图片的表单。我正在使用react-dropzone使它更酷; p 不幸的是,在选择图像后,我有未定义的src属性。 这是我的代码:
export const ImageInput = (props) => {
const imagePreviews = props.images.map(image => {
return <ImagePreview key={image.id} image={image.image}/>
})
return (
<div>
<Dropzone
className="dropzone"
multiple={true}
accept="image/*"
onDrop={props.addImage}> I STORE THE IMAGES IN PARENT COMPONENT
<p>drop or click here</p>
</Dropzone>
<ul>
{imagePreviews}
</ul>
</div>
)
}
这是单个ImagePreview组件
export const ImagePreview = (props) => {
let imagePreviewUrl = "";
let reader = new FileReader();
reader.readAsDataURL(props.image)
reader.onloadend = () => {
imagePreviewUrl = reader.result;
}
console.log(imagePreviewUrl)
return (
<li className="">
<img className="image-preview" src={imagePreviewUrl} />
</li>
)
}
使用反应工具浏览器我可以证明图像正确保存 image
我在哪里犯了错误?
答案 0 :(得分:0)
reader.onloadend是异步的,因此“ImagePreview”将在imagePreviewUrl具有值之前返回。您无法将此代码用于“ImagePreview”
class ImagePreview extends React.Component {
constructor() {
super();
this.state= {imagePreviewUrl: ''}
}
componentWillMount() {
let reader = new FileReader();
reader.readAsDataURL(props.image)
reader.onloadend = () => {
this.setState({imagePreviewUrl: reader.result})
}
}
}