Ill show with an example how React's two way binding works. Set up a React Application
App.js
import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';
class App extends Component {
state = {
persons: [
{
name: "VK",
age: 29
},
{
name: "HK",
age: 28
}
]
}
nameChangedHandler = (event) => {
this.setState(
{
persons: [
{
name: "VK",
age: 29
},
{
name: event.target.value,
age: 28
}
],
groupName: "Vishita"
}
);
}
render() {
return (
<div className="App">
<h1>Vinit Khandelwal</h1>
<p>And here is my resume</p>
<Person
name={this.state.persons[0].name}
age={this.state.persons[0].age} />
<Person
name={this.state.persons[1].name}
age={this.state.persons[1].age}
changed={this.nameChangedHandler} >Hobby: Shopping</Person>
</div>
);
}
}
export default App;
Person > Person.js
import React from 'react';
const person = (props) => {
return (
<div>
<p>I am {props.name}. I am {props.age} years old!</p>
<p onClick={props.click}>{props.children}</p>
<input type="text" onChange={props.changed} value={props.name} />
</div>
);
}
export default person;
This example shows two way binding in React by defining a function and calling the function, passing the event and using the event's value.
Comments
Post a Comment