Last active
December 11, 2020 11:10
-
-
Save achadha235/fbe533c23a32a9a73db86526ddfa1e6f to your computer and use it in GitHub Desktop.
Interactive React Component
This file contains hidden or 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
| /** | |
| * InteractiveComponent - Easily trigger event handler binding | |
| * to instance context with a customizable method naming convention | |
| e.g. | |
| class Foo extends InteractiveComponent { | |
| onFooClickedHandler(event){ | |
| console.log('state', this.state) | |
| } | |
| render() { | |
| // This handler will already be bound and we don't need | |
| // a call to this.onFooClickedHandler.bind in the constructor | |
| return <button onClick={this.onFooClickedHandler}/> | |
| } | |
| } | |
| */ | |
| import React from 'react'; | |
| export class InteractiveComponent extends React.Component { | |
| constructor(props) { | |
| super(props); | |
| const prototype = this.__proto__; | |
| const propNames = Object.getOwnPropertyNames(prototype); | |
| const hasSpecialPropName = (propName) => { | |
| const prefix = props.handlerPrefix || 'on'; | |
| const postfix = props.handlerPostfix || 'Handler'; | |
| return propName.length > prefix.length + postfix.length && | |
| propName.slice(0, prefix.length) === 'on' && | |
| propName.slice(propName.length - postfix.length); | |
| }; | |
| for (let i = 0; i < propNames.length; i++) { | |
| const propName = propNames[i]; | |
| if (typeof prototype[propName] === 'function' && | |
| hasSpecialPropName(propName) | |
| ) { | |
| prototype[propName] = prototype[propName].bind(this); | |
| } | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment