Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component, createContext } from 'react';
- const defaultValue = {
- firstName : '',
- lastName : ''
- };
- const FormContext = createContext(defaultValue);
- class Form extends Component {
- static contextType = FormContext;
- constructor(props) {
- super(props);
- this.state = {
- data: {}
- };
- }
- componentDidMount() {
- console.log('componentDidMount');
- console.log(this.state.data);
- let values = this.context.values;
- if(this.state.data !== values) {
- this.setState({data : values});
- }
- }
- componentDidUpdate() {
- console.log('componentDidUpdate');
- console.log(this.state.data);
- let values = this.context.values;
- if(this.state.data !== values) {
- this.setState({data : values});
- }
- }
- render() {
- return <div>
- <span id="result">{JSON.stringify(this.state.data)}</span>
- {this.props.children}
- </div>;
- }
- }
- class Field extends Component {
- static contextType = FormContext;
- _handleChange = (e) => {
- const { value } = e.target;
- this.context.change(this.props.name, value);
- }
- render() {
- let value = this.context.values[this.props.name];
- return <div>
- <input
- type="text"
- name={this.props.name}
- value={value ?? ''}
- onChange={this._handleChange}
- />
- </div>
- }
- }
- export default class App extends Component {
- constructor(props) {
- super(props);
- this.state = defaultValue
- this.changeValue = this.changeValue.bind(this);
- }
- changeValue(name, value) {
- let newState = this.state;
- newState[name] = value;
- this.setState(newState);
- }
- render() {
- return <FormContext.Provider value={{values : this.state, change : this.changeValue}}>
- <Form onChange={(data) => console.log("FormData: ", data)}>
- <Field name="firstName" />
- <Field name="lastName" />
- </Form>
- </FormContext.Provider>
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment