Last active
December 26, 2018 01:04
-
-
Save hoangthau/04101d2232d75771d5607e3df6b9c3c8 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 } from 'react'; | |
// đầu tiên tạo một context | |
const MyContext = React.createContext(); | |
// Sau đó tạo một Context Provider | |
class MyProvider extends Component { | |
state = { | |
name: 'Dan', | |
age: 100, | |
cool: true | |
} | |
render() { | |
return ( | |
<MyContext.Provider value={{ | |
state: this.state, | |
growAYearOlder: () => this.setState({ | |
age: this.state.age + 1 | |
}) | |
}}> | |
{this.props.children} | |
</MyContext.Provider> | |
) | |
} | |
} | |
const Family = (props) => ( | |
<div className="family"> | |
<Person /> | |
</div> | |
) | |
class Person extends Component { | |
render() { | |
return ( | |
<div className="person"> | |
<MyContext.Consumer> | |
{(context) => ( | |
<React.Fragment> | |
<p>Age: {context.state.age}</p> | |
<p>Name: {context.state.name}</p> | |
<button onClick={context.growAYearOlder}>🍰🍥🎂</button> | |
</React.Fragment> | |
)} | |
</MyContext.Consumer> | |
</div> | |
) | |
} | |
} | |
class App extends Component { | |
render() { | |
return ( | |
<MyProvider> | |
<div> | |
<p>This is a demo that we use Context API</p> | |
<Family /> | |
</div> | |
</MyProvider> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
create context