Created
April 23, 2018 20:48
-
-
Save kevinkassimo/74f5d6f119fd951e4b1bb28216b3cfbe 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
const createDecorator = () => { | |
const { | |
Provider: RawProvider, | |
Consumer: RawConsumer, | |
} = React.createContext(null); | |
const provider = (value) => (WrappedClass) => { | |
return class extends React.Component { | |
constructor(props) { | |
super(props); | |
this.$update = (v) => { | |
this.setState({ $value: v }); | |
}; | |
this.state = { | |
$value: value, | |
$update: this.$update, | |
}; | |
} | |
render() { | |
return ( | |
<RawProvider value={this.state}> | |
<WrappedClass {...this.props} /> | |
</RawProvider> | |
); | |
} | |
}; | |
} | |
const consumer = (ctxName) => (WrappedClass) => { | |
if (!ctxName) { | |
ctxName = 'ctx'; | |
} | |
const ctxUpdateName = `set${ ctxName.replace(/^\w/, (chr) => chr.toUpperCase()) }`; | |
return class extends React.Component { | |
render() { | |
const _consumerFunc = (context) => { | |
const _ctxProps = { | |
[ctxName]: context.$value, | |
[ctxUpdateName]: context.$update, | |
}; | |
return <WrappedClass {...this.props} {..._ctxProps}/> | |
} | |
return ( | |
<RawConsumer> | |
{_consumerFunc} | |
</RawConsumer> | |
); | |
} | |
}; | |
} | |
return { | |
provider, | |
consumer, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment