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?

onClickのイベント内の関数に引数を渡したい

Posted at

概要

onClickなどのイベント内の関数に引数を渡したかったので、その失敗内容と解決策を記載します。

失敗内容

onClick内の handleDeleteに indexを渡したかったが失敗
{tasks.map((task, index) => (
    <li key={`${task}${index}`}>
        {task} <button onClick={handleDelete(index)}>Delete</button>
    </li>
))}

いつものお作法にプラスしてカッコをつけて渡せばいいのかなぁと思って試しましたがダメでした。

解決策

onClick内にアロー関数を作ることで indexを渡せた
{tasks.map((task, index) => (
    <li key={`${task}${index}`}>
        {task} <button onClick={() => handleDelete(index)}>Delete</button>
    </li>
))}

終わりに

全然関係ないですが、イベントとか引数とか関数とか、それが何なのか言葉で説明できることも、コードの理解を深める一因になるのかなと感じました :writing_hand:

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?