2017-10-11 92 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) 

回答