在 React 中如何将道具和(事件)传递给 onClick 回调?

How do you pass a prop as well as the (event) to onClick callback in React?

我正在尝试添加一个 'Edit Load' 按钮,该按钮会在显示时添加到每篇文章中。我需要按钮将 {article.id} 作为道具传递给 onClick 函数 被称为:handleEdit。因此,当 EditLoadModal 的 showEdit 切换为打开时,我可以使用 article.id 通过更新传递给 EditLoadModal 组件的 loadID 道具来提取有关 'article' 的正确数据。

这样我就可以在 EditLoadModal.js 中使用该 ID 来提取相关数据并用于将更新后的信息写回数据库。

<EditLoadModal
        loadID={loadID}
        showEdit={showEdit}
        handleClick={handleEdit}
      />

      <Content>
        {props.loading && (
          <img alt="" src={require("./image/spinning-arrow.gif")} />
        )}
{props.articles.length > 0 &&
          props.articles.map((article, key) => (
            <Article key={key}>
              <SharedActor>
                <a>
                  <img src={article.actor.image} alt="" />
                  <div>
                    <span>{article.actor.title}</span>
                    <span>
                      {article.actor.date.toDate().toLocaleDateString()}
                    </span>
                    <span>{article.id}</span>
                  </div>
                </a>
                <a
                  href="/LoadManager"
                  onClick={handleEdit}
                  className="theme_btn"
                >
                  Edit Load
                </a>
              </SharedActor>

这是我的 handleEdit 函数

const [showEdit, setShowEdit] = useState("close");
const [loadID, setLoadId] = useState("1");

const handleEdit = (e) => {
    e.preventDefault();
    if (e.target !== e.currentTarget) {
      return;
    }

    switch (showEdit) {
      case "open":
        setShowEdit("close");
        break;
      case "close":
        setShowEdit("open");
        break;
      default:
        setShowEdit("close");
        break;
    }
  };

我在想我可以将 setLoadId(idProp) 添加到在 handleEdit(article.id) 内部传递的 prop 中。但不知道如何实现。

也许有更好的方法?

感谢您的帮助!

<a
  href="/LoadManager"
  onClick={(e) => handleEdit(e, article.id)}
  className="theme_btn"
>
  Edit Load
</a>

基本上不将handleEdit 直接传递给定位元素,而是有一个单独的回调来调用handleEdit。这样你就可以将任何你想要的参数传递给函数。