Advertisement
Guest User

Untitled

a guest
Jan 26th, 2018
4,706
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Parent extends React.Component {
  2.   constructor(props) {
  3.     super(props);
  4.  
  5.     this.state = {
  6.       input: null,
  7.       forwardValue: null
  8.     }
  9.  
  10.     this.handleClick = this.handleClick.bind(this);
  11.     this.handleChange = this.handleChange.bind(this);
  12.   }
  13.  
  14.   handleChange(event) {
  15.     this.setState({ input: event.target.value });
  16.   }
  17.  
  18.   handleClick() {
  19.     this.setState({ forwardValue: this.state.input });
  20.   }
  21.  
  22.   render() {
  23.     return(
  24.       <div>
  25.         <input onChange={this.handleChange} type="number" />
  26.         <button onClick={this.handleClick}>Propagate to child</button>
  27.         {this.state.forwardValue && <Child value={this.state.forwardValue}/>}
  28.       </div>
  29.     );
  30.   }
  31. }
  32.  
  33. class Child extends React.Component {
  34.   constructor(props) {
  35.     super(props);
  36.  
  37.     this.state = {
  38.       fromParent: Number(props.value),
  39.       current: Number(props.value),
  40.     }
  41.  
  42.     this.handleIncrement = this.handleIncrement.bind(this);
  43.     this.handleDecrement = this.handleDecrement.bind(this);
  44.   }
  45.  
  46.   componentWillReceiveProps(nextProps) {
  47.     if (nextProps.value != this.state.fromParent) {
  48.       this.setState({
  49.         fromParent: Number(nextProps.value),
  50.         current: Number(nextProps.value),
  51.       })
  52.     }
  53.   }
  54.  
  55.   handleIncrement() {
  56.     this.setState({ current: this.state.current + 1 })
  57.   }
  58.  
  59.   handleDecrement() {
  60.     this.setState({ current: this.state.current - 1 })
  61.   }
  62.  
  63.   render() {
  64.     return(
  65.       <div>
  66.         <label>{this.state.current}</label>
  67.         <button onClick={this.handleIncrement}>+</button>
  68.         <button onClick={this.handleDecrement}>-</button>
  69.       </div>
  70.     );
  71.   }
  72. }
  73.  
  74. ReactDOM.render(
  75.   <Parent />,
  76.   document.getElementById('root')
  77. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement