RotLenin

Untitled

Apr 12th, 2022
974
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.   secondName : '',
  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.  
  48.         let inputValue;
  49.  
  50.         if(!values[this.props.name]){
  51.           inputValue = '';
  52.         }
  53.  
  54.         return <div>
  55.           <input
  56.             type="text"
  57.             name={this.props.name}
  58.             value={inputValue}
  59.             onChange={(e) => change(this.props.name, e.target.value)}
  60.           />
  61.         </div>
  62.       }
  63.       }
  64.     </FormContext.Consumer>
  65.   }
  66. }
  67.  
  68. export default class App extends Component {
  69.   render() {
  70.     return <Form>
  71.       <Field name="firstName" />
  72.       <Field name="lastName" />
  73.     </Form>
  74.   }
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment