Skip to content

Instantly share code, notes, and snippets.

@mikezimm
Last active November 11, 2019 00:45
Show Gist options
  • Save mikezimm/c87ea48f0083c39a4a180c6d438468ed to your computer and use it in GitHub Desktop.
Save mikezimm/c87ea48f0083c39a4a180c6d438468ed to your computer and use it in GitHub Desktop.
How to bind onClick this & event?
// NOTE FOR FUTURE ReWriting:
// Check this post and see if using arrow function will work.
// https://stackoverflow.com/questions/42576198/get-object-data-and-target-element-from-onclick-event-in-react-js?fbclid=IwAR3a8oYBmVarTQy3lLfQFA-xZ8sv_0pSDd9Mag_4m3fWF9rGZuRblKK3dyg
public constructor(props:IPivotTilesProps){
super(props);
this.state = {
// .... stuff deleted //
};
// .... stuff deleted //
this.onLinkClick = this.onLinkClick.bind(this);
}
// .... stuff deleted //
public render(): React.ReactElement<IPivotTilesProps> {
// .... stuff deleted //
return (
<Pivot
style={{ flexGrow: 1, paddingLeft: '10px' }}
linkSize= { pivotOptionsGroup.getPivSize(this.props.setPivSize) }
linkFormat= { pivotOptionsGroup.getPivFormat(this.props.setPivFormat) }
onLinkClick= { this.onLinkClick.bind(this) } //{this.specialClick.bind(this)}
defaultSelectedKey={ defIndex }
headersOnly={true}>
{this.createPivots(this.state,this.props)}
</Pivot>
);
}
public onLinkClick = (item): void => {
console.log('onLinkClick item: ', item); // This will get me information about the Pivot I clicked on (need heading)
console.log('onLinkClick this: ', this); // This will get me the react component's "this"
//UPDATE THIS IS WHAT WORKS:
// If you try to refer to "event" directly (event.ctrlKey) it does not work.
// BUT if you assign it to e first, then it works :)
let e: any = event;
if (e.ctrlKey) {
//window.open(this.props.listWebURL, '_blank');
//event.preventDefault();
//return ;
alert('Hi! CTRL key was pressed! ' + item.props.headerText);
}
// NOTE: This was my original code WHICH DID NOT WORK... See notes above.
// But I also need to find a way to get the event so I can tell if any special keys are pressed...
// I copied this code from another component's onClick and I can get both props and the event by just passing in the event.
// The only difference is in my other component, I'm not passing it to an Office UI Fabric component
// What I want is perform extra action if the CTRL-key is pressed when clicking.
if (event.ctrlKey) {
//window.open(this.props.listWebURL, '_blank'); // My current code gets the link to open
//event.preventDefault();
//return ;
alert('Hi! CTRL key was pressed!');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment