javascript - Recent Camera gets overrided with the default image -
i have image grid, designed have add more button, when clicked on it. new image placeholder should appear default image, when clicked on camera gets invoked , should update default image picture taken. in case, camera picture not getting updated default picture stays. when clicked on add more, instead of default picture recent camera picture getting appeared. think there problem rendering part of code.
here code
var summary = react.createclass({ getinitialstate: function(){ return { pictriggers: [], number:0, image:"https://www.bignerdranch.com/img/blog/2014/07/button-2.png" } }, camera: function(){ var = this; var image = this.state.image; navigator.camera.getpicture(onsuccess, onfail, { quality: 50, destinationtype: camera.destinationtype.data_url }); function onsuccess(imagedata) { console.log(imagedata); var finalimage = "data:image/jpeg;base64," + imagedata; that.setstate({image: finalimage}); } function onfail(message) { alert('failed because: ' + message); } }, newbutton: function(){ var number = this.state.number; number = number+1; var pictriggers = this.state.pictriggers; pictriggers.push(<img id={"div"+number} src={this.state.image} onclick={this.camera} classname="addpicture"/>); this.setstate({pictriggers: pictriggers, number:number}); }, render: function(){ return( <div> {this.state.pictriggers} <button onclick={this.newbutton}> {this.state.number>0?"add more":"add picture"} </button> <button classname="uploadselected"> upload selected </button> </div>); } });
if i'm following correctly, flow here looks like:
- first render:
add picture
button rendered - if button clicked, default image shown via
#newbutton
- if image clicked,
#camera
function gets image asynchronously , updates state image. - this trigger
#render
. haven't done @ point add new itempictriggers
new image, old image displays. - when click
add more
, runs#newbutton
again , image rendered.
i think make life easier maintaining array of imgsrcs
instead of array of rendered components. when camera image, add array:
var finalimage = "data:image/jpeg;base64," + imagedata; // better not mutate state directly, make new array // slice, dropping default image var imgsrcs = this.state.imgsrcs.slice(0, -1); imgsrcs.push(finalimage); this.setstate({ imgsrcs: imgsrcs });
and in #newbutton
, add default image end of array:
var imgsrcs = this.state.imgsrcs.concat([this.state.defaultimage]); this.setstate({ imgsrcs: imgsrcs });
now have simple rendering problem, rendering list of images, instead of hard state problem, making sure pre-rendered components in sync each time #render
called.
Comments
Post a Comment