import React from '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 do 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 do paciente"/>
</label>
</li>
<li>
<button type="button" onClick={this.handleSubmit}> Submit </button>
</li>
</ul>
</form>
);
}
}
Objective: Get data from this form and display it in other page(Sidebar.js) So after submit those informations in that form, I want to get those informations using SetState and display only the patientname in a list. How do I do that using SetState?
First of all, your code has several problems:
Use onChange
instead of OnChange
:
<input type="text" onChange={this.handlePatientName} />
Your event handlers are not bound to the class instance, so this
will be undefined in your callback and this.setState()
will fail. You can solve this by using .bind(this)
:
onChange={this.handlePatientName.bind(this)}
Or by binding the handlers in your constructor:
constructor(){ this.handlePatientName = this.handlePatientName.bind(this); }
Or by using class properties and defining the handlers as arrow functions:
handlePatientName = (e) => { }
You should name your component Form
or something other than form
, since form
is used for the HTML form element .
Once all that is done, you are still not exposing the form state to "other pages". To do that you should provide callback props to pass the data outside the component:
handlePatientName = (e) => { let patientName = e.target.value; this.setState({ patientName }); this.props.onPatientNameChange(patientName); }
Now from a parent page you can capture the changes:
class Parent extends React.Component { handlePatientNameChange = (patientName) => { console.log("Patient name changed to:", patientName); } render() { return ( <Form onPatientNameChange={this.handlePatientNameChange} /> ); } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.