Created
March 18, 2017 21:25
-
-
Save olivierlesnicki/88a2b027b0a0358714c757d15816317c 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
import React, { Component } from 'react'; | |
const Stateful = fn => { | |
return class Stateful extends Component { | |
constructor() { | |
super(...arguments); | |
this.component = this.component.bind(this); | |
this.state = {}; | |
} | |
component(callback) { | |
return (...args) => { | |
return Promise | |
.resolve(callback.call(null, this.props, this.state, ...args)) | |
.then(newState => { | |
this.setState(newState); | |
}); | |
} | |
} | |
render() { | |
return fn.call(this.component, this.props, this.state); | |
} | |
} | |
}; | |
function handleClick(props, state, event) { | |
if (event.button === 1) { | |
// Middle click resets state to zero | |
return { count: 0 }; | |
} | |
if (props.onClick) { | |
props.onClick(); | |
} | |
return { count: state ? state.count + 1 : 0 }; | |
} | |
export default Stateful(function Counter(props, state) { | |
return ( | |
<div> | |
Clicked {state ? state.count : 0} times | |
<button onClick={this(handleClick)} style={{ width: props.width }} /> | |
</div> | |
); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment