javascript - React: Controlling input value with both props and state -
given react component controlled input, able to:
- set value of input parent's state
- allow user change input value
- 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
Post a Comment