javascript - How to use SetState to get data after submit some information in a form? -
import react 'react' export default class form extends react.component{ /// handle submit handlesubmit(e){ e.preventdefault(); } /// handle patientname handlepatientname(e) { this.setstate({ patientname: e.target.value }) } // handle patient disease handlepatientdisease(e){ this.setstate({ patientdisease: e.target.value }) } // handle patient present illness handlepatientpresentillness(e){ this.setstate({ patientpresentillness: e.target.value }) } render () { return ( <form> <ul> <li> <label> patient name</label> <input type="text" name="patientname" placeholder="nome paciente" onchange={this.handlepatientname} /> </li> <li> <label> patient disease <input type="text" name="patientdisease" placeholder="disease"/> </label> </li> <li> <label> histórico <input type="text" name="patientpresentillness" placeholder="historia paciente"/> </label> </li> <li> <button type="button" onclick={this.handlesubmit}> submit </button> </li> </ul> </form> ); } }
objective: data form , display in other page(sidebar.js) after submit informations in form, want informations using setstate , display patientname in list. how do using setstate?
first of all, code has several problems:
use
onchange
instead ofonchange
:<input type="text" onchange={this.handlepatientname} />
your event handlers not bound class instance,
this
undefined in callback ,this.setstate()
fail. can solve using.bind(this)
:onchange={this.handlepatientname.bind(this)}
or binding handlers in constructor:
constructor(){ this.handlepatientname = this.handlepatientname.bind(this); }
or using class properties , defining handlers arrow functions:
handlepatientname = (e) => { }
you should name component
form
or otherform
, sinceform
used html form element.once done, still not exposing form state "other pages". should provide callback props pass data outside component:
handlepatientname = (e) => { let patientname = e.target.value; this.setstate({ patientname }); this.props.onpatientnamechange(patientname); }
now parent page can capture changes:
class parent extends react.component { handlepatientnamechange = (patientname) => { console.log("patient name changed to:", patientname); } render() { return ( <form onpatientnamechange={this.handlepatientnamechange} /> ); } }
Comments
Post a Comment