Extend react.Component class
- Use bind(this)
import * as React from 'react';
export interface TempProps {
title: string;
onButtonClick: (v: string) => void;
}
export class TempComponent extends React.Component<TempProps> {
public componentDidMount() {
this.handleOnButtonClick = this.handleOnButtonClick.bind(this);
}
public render() {
return (
<div>
<button onClick={this.handleOnButtonClick}>aaaa</button>
</div>
);
}
private handleOnButtonClick() {
this.props.onButtonClick(this.props.title);
}
}
2.Use arrow method()=>{}
import * as React from 'react';
export interface TempProps {
title: string;
onButtonClick: (v: string) => void;
}
export class TempComponent extends React.Component<TempProps> {
public render() {
return (
<div>
<button onClick={_ => this.handleOnButtonClick()}>aaaa</button>
</div>
);
}
private handleOnButtonClick() {
this.props.onButtonClick(this.props.title);
}
}
Use hook
- Use arrow method
import * as React from 'react';
export interface TempProps {
title: string;
onButtonClick: (v: string) => void;
}
export const TempComponent: React.FC<TempProps> = ({ title, onButtonClick }) => {
const handleOnButtonClick = () => {
onButtonClick(title);
};
return (
<div>
<button onClick={handleOnButtonClick}>aaaa</button>
</div>
);
};
2.Without using bing this, it also works in react hook.
import * as React from 'react';
export interface TempProps {
title: string;
onButtonClick: (v: string) => void;
}
export const TempComponent: React.FC<TempProps> = ({ title, onButtonClick }) => {
function handleOnButtonClick() {
onButtonClick(title);
};
return (
<div>
<button onClick={handleOnButtonClick}>aaaa</button>
</div>
);
};