Skip to content

Instantly share code, notes, and snippets.

@mayneyao
Last active January 7, 2019 03:15
Embed
What would you like to do?
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