0
1

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.

ReactでonClickで指定したイベントハンドラがレンダー時に発火する

Posted at

環境

  • react 17.0.1

内容

Material-UIのchipのタイトルをイベントハンドラの引数に指定したら、レンダー時に発火した。

レンダー時に発火するコード
export default function TagsSerch() {
    const handleClick = (title) => {
        console.info(title);
    };

    /* 色々省略 */

    return (
        <Box>
            <Typography variant="subtitle1">タグ検索</Typography>
            {tagList.map((tag, index) => (
                <Chip
                className={classes.tags}
                name={tag.title}
                label={tag.title}
                clickable
                color="primary"
                size="small"
                onClick={handleClick(tag.title)}    /* ⇦ここ */
                key={tag.title}
                />
            ))}
        </Box>

    );
}

React公式サイトによると、こんな感じで引数を渡してくださいとのこと。

レンダー時に発火せず引数をイベントハンドラに渡す
export default function TagsSerch() {
    const handleClick = (title, e) => {
        console.info(title);
        console.info(e);
    };

    /* 色々省略 */

    return (
        <Box>
            <Typography variant="subtitle1">タグ検索</Typography>
            {tagList.map((tag, index) => (
                <Chip
                className={classes.tags}
                name={tag.title}
                label={tag.title}
                clickable
                color="primary"
                size="small"
                onClick={onClick={(e) => handleClick(tag.title, e)}}    /* アロー関数かまして呼び出すよ */
                key={tag.title}
                />
            ))}
        </Box>

    );
}

今回はイベントオブジェクトはいらないので、最終的にこんな感じになりました。

レンダー時に発火せず引数をイベントハンドラに渡す(イベントオブジェクトなし)
export default function TagsSerch() {
    const handleClick = (title) => {
        console.info(title);
    };

    /* 色々省略 */

    return (
        <Box>
            <Typography variant="subtitle1">タグ検索</Typography>
            {tagList.map((tag, index) => (
                <Chip
                className={classes.tags}
                name={tag.title}
                label={tag.title}
                clickable
                color="primary"
                size="small"
                onClick={onClick={() => handleClick(tag.title)}}    /* アロー関数かまして呼び出すよ */
                key={tag.title}
                />
            ))}
        </Box>

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?