2017-10-11 88 views
0

我正在尝试在使用FileReader的道具上设置默认图像。我希望图像在组件装入时加载componentDidMount(){...},并在用户决定不上载图像时使用。我一直无法得到这个工作,请帮助。 avatar是我想用作默认的图像。 <ImageUpload />使用base64url编码工作。 x.img最初是{}。我试图拨打_handleImageChange并通过avatar。我试图在#profile-img上使用defaultValue={avatar},以及其他一些我以后被遗忘的东西 - 但没有运气。任何有识之士将不胜感激。提前感谢!下面的代码:React/Javascript - FileReader/<input/> /添加图片

import React from 'react'; 
import {connect} from 'react-redux'; 
import './imageupload.css'; 
import {addImg} from '../../actions/index2'; 
import avatar from './avatar.jpg'; 



export class ImageUpload extends React.Component { 
constructor(props) { 
    super(props) 
    this.state = { 
    img:{} 
    }; 
    this._handleImageChange = this._handleImageChange.bind(this); 
    this._makeFile = this._makeFile.bind(this); 
} 

componentDidMount() { 

} 

_handleImageChange(e) { 
    e.preventDefault(); 
    let reader = new FileReader(); 
    let file = e.target.files[0]; 
    console.log('e.target.files[0]', e.target.files[0]) 
    reader.onloadend =() => { 

     let serializedFile = { 
      lastModified: file.lastModified, 
      lastModifiedDate:file.lastModifiedDate, 
      name:file.name, 
      size:file.size, 
      type:file.type, 
      webkitRelativePath:file.webkitRelativePath 
     } 
     this.props.dispatch(addImg({ 
      file: serializedFile, 
      imagePreviewUrl: reader.result 
     })) 
     if (this.props.moveImg) { 
      this.props.moveImg({ 
      file: serializedFile, 
      imagePreviewUrl: reader.result 
     }) 
     } 
    } 
    reader.readAsDataURL(file) 
} 

render() { 
    let x = this.props; 
    let {imagePreviewUrl} = x.img ; 
    let $imagePreview = null; 
    if (imagePreviewUrl) { 
    $imagePreview = (<img id='img-preview' alt='file to upload' src={imagePreviewUrl} />); 
    } 

    return (
    <div> 
     <input id='profile-img' type="file" onChange={this._handleImageChange } /> 
     {$imagePreview} 
     <button onClick={()=>console.log(this.props)}>see state</button> 
    </div> 
) 
} 

    } 

    export const mapStateToProps = state => { 
    return { 
    img:state.oneReducer.img 
    } 
    } 

    export default connect(mapStateToProps)(ImageUpload) 

回答