Skip to content

Instantly share code, notes, and snippets.

@mayneyao
Last active January 7, 2019 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayneyao/547504c1cf43eb53c396c9fe630030b0 to your computer and use it in GitHub Desktop.
Save mayneyao/547504c1cf43eb53c396c9fe630030b0 to your computer and use it in GitHub Desktop.
React(16.3+) Context API
import React, {Component, createContext} from 'react';
import {setName} from "./actions";
const Context = createContext();
export class Provider extends Component {
genActions = () => {
let actions = {};
actions['setName'] = setName.bind(this);
return actions;
};
constructor() {
super();
this.state = {
name: 'Mayne'
}
}
render() {
return <div>
<Context.Provider value={{
...this.state,
...this.genActions()
}}>
{this.props.children}
</Context.Provider>
</div>
}
}
export function connectWithStore(OtherComponent) {
return class extends Component {
render() {
return (
<div>
<Context.Consumer>
{
(context) => <OtherComponent {...context} {...this.props}/>
}
</Context.Consumer>
</div>
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment