簡體   English   中英

如何解決高階函數的問題?

[英]How to solve a problem with a higher order function?

我似乎並不完全理解“關閉”是如何工作的。 更改時我有一個輸入,我需要調用函數並向它傳遞 2 個參數。 但我也需要這個事件的事件。

我下面的版本不起作用。 只有函數的第一部分可以工作,而第二部分(我返回第二個函數)不起作用。 不幸的是,我無法理解我的錯誤是什么以及如何“關閉”到底。

第二個小問題——如果我正在反應,如何在此處輸入事件?

const handleChangeClosure = (userId: string, role: string) => (event: ???) => {
  const { checked } = event.target;
  dispatch(addOrDeleteRoleAction(userId, role, checked, dispatch));
};

<input type="checkbox" onChange={() => handleChangeClosure(user.userId, "Controller")}/>

代替

<input type="checkbox" onChange={() => handleChangeClosure(user.userId, "Controller")}/>

<input type="checkbox" onChange={handleChangeClosure(user.userId, "Controller")}/>

handleChangeClosure函數返回一個函數,而onChange事件需要一個函數。 所以你不需要()=>它將它包裝在另一個函數中。

或者,這也可以:

<input type="checkbox" onChange={(ev) => handleChangeClosure(user.userId, "Controller")(ev)}/>

但這只是更無用的代碼。

通過使用onChange={() => ...} ,您將丟失event參數。

你想要的是

<input type="checkbox" onChange={handleChangeClosure(user.userId, "Controller")}/>

您的高階函數返回一個新的事件處理函數,該函數將附加到更改事件。

僅供參考, event的類型是React.ChangeEvent<HTMLInputElement>

const handleChangeClosure =
  (userId: string, role: string) =>
  (event: React.ChangeEvent<HTMLInputElement>) => {
    const { checked } = event.target;
    dispatch(addOrDeleteRoleAction(userId, role, checked, dispatch));
  };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM