我正在努力使我的 React.JS 應用程式符合可訪問性標準。
作為練習的一部分onKeyDown,我在使用onClick處理程式的地方添加了處理程式。我還用一個特殊的包裝函式來包裝這些處理??程式,該函式檢查按下了哪個鍵。實際代碼如下:
import { KeyboardEvent } from 'react';
enum Keys {
TAB = 9,
}
const handleKeyPress = (cb: () => void) => (e: KeyboardEvent) => {
if (e.keyCode !== Keys.TAB) cb();
};
export { handleKeyPress };
我用它作為:
<div
className={classes.link_complete}
onClick={handleOnClick}
onKeyDown={handleKeyPress(() => {
handleOnClick();
})}
tabIndex={0}
role="button"
>
這作業正常。但是,在某些情況下,我想將實際事件作為引數傳遞給由函式包裝的handleKeyPress函式。那對我不起作用。我試過:
onClick={handleViewInfoClick}
onKeyDown={(e) => {
console.log('detected keydown');
handleKeyPress(() => {
console.log('inside handler');
handleViewInfoClick(e);
});
}}
那是行不通的。檢測到 Keydown 事件,因此我看到detected keydown列印。然而,里面的代碼并沒有被呼叫。
這樣做的正確方法是什么?
uj5u.com熱心網友回復:
問題是handleKeyPress回傳一個函式(這是有道理的,因為您通常使用 的回傳值onKeyDown),但是您沒有在您嘗試使用事件物件的示例中呼叫它,您只是呼叫handleKeyPress來創建函式,然后不呼叫該函式。
我會修改handleKeyPress以便它傳遞事件物件:
const handleKeyPress = (cb: (e: KeyboardEvent) => void) => (e: KeyboardEvent) => {
// ^^^^^^^^^^^^^^^^
if (e.keyCode !== Keys.TAB) cb(e);
// ^
};
然后用法幾乎與您的原始用法完全一樣,您只需包含處理程式:
<div
className={classes.link_complete}
onClick={handleOnClick}
onKeyDown={handleKeyPress((e) => handleViewInfo(e))}
tabIndex={0}
role="button"
>
或更簡潔地說:
<div
className={classes.link_complete}
onClick={handleOnClick}
onKeyDown={handleKeyPress(handleViewInfo)}
tabIndex={0}
role="button"
>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404539.html
標籤:
