RotLenin

Untitled

Apr 11th, 2022
984
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { Component, createContext }  from 'react';
  2.  
  3. const defaultValue = {
  4.   firstName : '',
  5.   lastName : ''
  6. };
  7.  
  8. const FormContext = createContext(defaultValue);
  9.  
  10. class Form extends Component {
  11.   static contextType = FormContext;
  12.  
  13.   constructor(props) {
  14.     super(props);
  15.  
  16.     this.state = {
  17.       data: {}
  18.     };
  19.   }
  20.  
  21.   componentDidMount() {
  22.     console.log('componentDidMount');
  23.     console.log(this.state.data);
  24.     let values = this.context.values;
  25.  
  26.     if(this.state.data !== values) {
  27.       this.setState({data : values});
  28.     }
  29.   }
  30.   componentDidUpdate() {
  31.     console.log('componentDidUpdate');
  32.     console.log(this.state.data);
  33.     let values = this.context.values;
  34.  
  35.     if(this.state.data !== values) {
  36.       this.setState({data : values});
  37.     }
  38.   }
  39.  
  40.   render() {
  41.     return <div>
  42.       <span id="result">{JSON.stringify(this.state.data)}</span>
  43.       {this.props.children}
  44.     </div>;
  45.   }
  46. }
  47.  
  48. class Field extends Component {
  49.   static contextType = FormContext;
  50.  
  51.   _handleChange = (e) => {
  52.     const { value } = e.target;
  53.     this.context.change(this.props.name, value);
  54.   }
  55.  
  56.   render() {
  57.     let value = this.context.values[this.props.name];
  58.     return <div>
  59.         <input
  60.           type="text"
  61.           name={this.props.name}
  62.           value={value ?? ''}
  63.           onChange={this._handleChange}
  64.         />
  65.     </div>
  66.   }
  67. }
  68.  
  69. export default class App extends Component {
  70.   constructor(props) {
  71.     super(props);
  72.     this.state = defaultValue
  73.     this.changeValue = this.changeValue.bind(this);
  74.   }
  75.  
  76.   changeValue(name, value) {
  77.     let newState = this.state;
  78.     newState[name] = value;
  79.     this.setState(newState);
  80.   }
  81.  
  82.   render() {
  83.     return <FormContext.Provider value={{values : this.state, change : this.changeValue}}>
  84.       <Form onChange={(data) => console.log("FormData: ", data)}>
  85.         <Field name="firstName" />
  86.         <Field name="lastName" />
  87.       </Form>
  88.     </FormContext.Provider>
  89.   }
  90. }
  91.  
Advertisement
Add Comment
Please, Sign In to add comment