index.js
import React from "react";
import ReactDOM from "react-dom";
import Provider, {Context} from '../context'
function App() {
return (
<Provider>
<div className="App">
<h1>This is the heading</h1>
<Context.Consumer>
{ctx => ctx.number}
</Context.Consumer>
<Context.Consumer>
{ctx => <button onClick={ctx.inc}>inc</button>}
</Context.Consumer>
</div>
</Provider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
context.js (or store.js)
import React from "react";
import ReactDOM from "react-dom";
export const Context = React.createContext();
class Provider extends React.Component {
state = {
number: 0,
inc: () => this.setState({ number: this.state.number + 1 })
};
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
);
}
}
export default Provider;
No comments:
Post a Comment