RotLenin

Untitled

Apr 12th, 2022
629
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 : null,
  5.   lastName : null
  6. };
  7.  
  8. const FormContext = createContext(defaultValue);
  9.  
  10. class Form extends Component {
  11.   constructor(props) {
  12.     super(props);
  13.  
  14.     this.state = {
  15.       data: defaultValue
  16.     };
  17.  
  18.     this.changeValue = this.changeValue.bind(this);
  19.   }
  20.  
  21.   changeValue (name, value) {
  22.     let newData = this.state.data;
  23.     newData[name] = value;
  24.     this.setState(newData);
  25.   }
  26.  
  27.   render() {
  28.     return <FormContext.Provider value={{values : this.state.data, change : this.changeValue}}>
  29.       <div>
  30.         <span id="result">{JSON.stringify(this.state.data)}</span>
  31.         {this.props.children}
  32.       </div>
  33.     </FormContext.Provider>
  34.   }
  35. }
  36.  
  37. class Field extends Component {
  38.   _handleChange = (e) => {
  39.     const { value } = e.target;
  40.     this.setState({ value });
  41.   }
  42.  
  43.   render() {
  44.     return <FormContext.Consumer>
  45.       {value => {
  46.         const {values, change} = value;
  47.         return <div>
  48.           <input
  49.             type="text"
  50.             name={this.props.name}
  51.             value={values[this.props.name] ?? ''}
  52.             onChange={(e) => change(this.props.name, e.target.value)}
  53.           />
  54.         </div>
  55.       }
  56.       }
  57.     </FormContext.Consumer>
  58.   }
  59. }
  60.  
  61. export default class App extends Component {
  62.   render() {
  63.     return <Form>
  64.       <Field name="firstName" />
  65.       <Field name="lastName" />
  66.     </Form>
  67.   }
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment