Created
April 7, 2015 10:15
-
-
Save frostney/c6e2cc1c541819b64c5b to your computer and use it in GitHub Desktop.
React mixins with decorators
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
var ReactMixin = function(...mixins) { | |
return function(Component) { | |
mixins.forEach(function(mixin) { | |
Object.keys(mixin).forEach(function(methodName) { | |
const methodValue = mixin[methodName]; | |
if (methodName === 'statics') { | |
Object.keys(mixin.statics).forEach(function(staticProp) { | |
const staticValue = mixin.statics[staticProp]; | |
Component[staticProp] = staticValue; | |
}); | |
} else { | |
Component.prototype[methodName] = methodValue; | |
} | |
}); | |
}); | |
}; | |
}; |
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
// Babel >= 5.0.0 is required and must be set to include Stage 1 ES7 proposals | |
const Alerter = { | |
showAlert() { | |
alert('Hey there!'); | |
} | |
}; | |
@ReactMixin(Alerter) | |
class AlertMe extends React.Component { | |
render() { | |
return <button onClick={this.showAlert}>Click me</button> | |
} | |
} | |
// Assuming a container element exists | |
React.render(<AlertMe />, document.getElementById('container')); |
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
// Multiple mixins and static methods are supported as well | |
const Alerter = { | |
showAlert() { | |
alert('Hey there!'); | |
} | |
}; | |
const Boom = { | |
statics: { | |
boom() { | |
alert('Boom'); | |
} | |
} | |
}; | |
@ReactMixin(Alerter, Boom) | |
class AlertMe extends React.Component { | |
render() { | |
return <button onClick={this.showAlert}>Click me</button> | |
} | |
} | |
AlertMe.boom(); | |
// Assuming a container element exists | |
React.render(<AlertMe />, document.getElementById('container')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment