Last active
January 7, 2019 03:15
-
-
Save mayneyao/547504c1cf43eb53c396c9fe630030b0 to your computer and use it in GitHub Desktop.
React(16.3+) Context API
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, 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