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