Last active
September 26, 2019 16:29
-
-
Save Palatnyi/9a6cb87224d99a86391add2f06e6a4b1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {Component, PureComponent, createContext} from 'react'; | |
const Context = createContext(); | |
class User { | |
constructor(getState, rootUpdater) { | |
this._getState = getState; | |
this._rootUpdater = rootUpdater; | |
this.name = ''; | |
this.surname = ''; | |
} | |
_setValue = (value = {}) => { | |
this._rootUpdater({ | |
user: { | |
setName: this.setName, | |
setSurname: this.setSurname, | |
...this._getState().user, | |
...value | |
} | |
}); | |
}; | |
setName = (name = '') => { | |
this._setValue({name}); | |
} | |
setSurname = (surname = '') => { | |
this._setValue({surname}); | |
} | |
} | |
class Store extends Component { | |
constructor(props) { | |
super(props); | |
this.rootUpdater = (data = {}) => { | |
this.setState({ | |
...this.state, | |
...data | |
}) | |
}; | |
this.getState = () => { | |
return this.state; | |
}; | |
const user = new User(this.getState, this.rootUpdater); | |
this.state = {user}; | |
} | |
render() { | |
return ( | |
<Context.Provider value={this.state}> | |
{this.props.children} | |
</Context.Provider> | |
); | |
} | |
} | |
function Layout() { | |
return ( | |
<div> | |
<Title /> | |
<Input /> | |
</div> | |
); | |
} | |
class Title extends PureComponent { | |
static contextType = Context; | |
render() { | |
return ( | |
<div> | |
<h3> | |
name {this.context.user.name} | |
</h3> | |
<h3> | |
surname {this.context.user.surname} | |
</h3> | |
</div> | |
); | |
} | |
} | |
class Input extends PureComponent { | |
static contextType = Context; | |
constructor(props) { | |
super(props); | |
this.nameInput = React.createRef(); | |
this.surnameInput = React.createRef(); | |
} | |
setName = (e) => { | |
this.context.user.setName(e.target.value); | |
} | |
setSurname = (e) => { | |
this.context.user.setSurname(e.target.value); | |
} | |
render() { | |
return ( | |
<div> | |
<div> | |
<p>change name </p> | |
<input ref={this.nameInput} onChange={this.setName} /> | |
</div> | |
<div> | |
<p>change name </p> | |
<input ref={this.surnameInput} onChange={this.setSurname} /> | |
</div> | |
</div> | |
); | |
} | |
} | |
export function App() { | |
return ( | |
<Store> | |
<Layout /> | |
</Store> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment