Created
October 5, 2017 02:56
-
-
Save richseviora/57f969daa8ff576c8f52d1d279e6909e to your computer and use it in GitHub Desktop.
Handler Allocation Examples
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
class ParentComponent extends React.Component<any, any>{ | |
render(): JSX.Element { | |
return ( | |
<div> | |
<EveryRenderComponent id={1} doTheThing={this.doTheNumberThing} /> | |
<OnMountComponent id={2} doTheThing={this.doTheNumberThing} /> | |
<OnParentComponent id={3} doTheThing={this.doTheDataSetThing} /> | |
</div> | |
) | |
} | |
doTheNumberThing = (id: number) => { | |
console.log("Zhu Li! Do the thing", id); | |
} | |
doTheDataSetThing = (event: any) => { | |
console.log("Zhu Li! Do the thing", event.target.dataSet.id); | |
} | |
} | |
// Allocates handler on every render. IS BAD. | |
class EveryRenderComponent extends React.Component<any, any> { | |
render(): JSX.Element { | |
return ( | |
<button onClick={() => this.props.doTheThing(this.props.id)}/> | |
); | |
} | |
} | |
// Allocates handler on initializing only. | |
class OnMountComponent extends React.Component<any, any> { | |
render(): JSX.Element { | |
return ( | |
<button onClick={this.doTheThing}/> | |
); | |
} | |
private doTheThing = (event: any) => { | |
this.props.doTheThing(this.props.id); | |
} | |
} | |
// Handler is allocated once per parent. Seems ideal for huge lists of items. | |
class OnParentComponent extends React.Component<any, any> { | |
render(): JSX.Element { | |
return ( | |
<button onClick={this.props.doTheThing} data-id={this.props.id}/> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment