javascript - React: Controlling input value with both props and state -


given react component controlled input, able to:

  1. set value of input parent's state
  2. allow user change input value
  3. update parent's state after user submits , input passes validation.

i can accomplish 1 , 2 snippet below, since value came childcomponent via props, i'm not sure how can change input value without changing value of myinput on parent.

class childcomponent extends react.component {     render(){         return <input type="text" value={this.props.inputvalue} onchange={this.handlechange.bind(this)} />     }       handlechange(e){         this.props.oninputchange(e.target.value);     }     handlesubmit(){         // validation here, it passes...         this.props.handlesubmit();     } }  class parentcomponent extends react.component{     constructor(){       super();       this.state = {myinput: ""};     }     render(){         return <childcomponent inputvalue={this.state.myinput} oninputchange={this.handlechange.bind(this)} />     }     handlechange(newvalue){         this.setstate({myinput: newvalue});     }     handlesubmit(){         // on server     } } 

then need move state child component, instead of rendering props.inputvalue directly. you'd move handlechange child.

set initial value props.inputvalue in getinitialstate, make sure update child state in componentwillreceiveprops.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -