0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Two ways to trigger event in react component.

Last updated at Posted at 2020-11-27

Extend react.Component class

  1. 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

  1. 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>
    );
};
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?