Javascript useCallback不继承父道具
我检测到一个组件中的按键,该组件通过一个道具,currentDialog知道应用程序中其他地方当前打开的对话框组件。通常,我可以在嵌套函数中访问此道具,但在使用Javascript useCallback不继承父道具,javascript,reactjs,Javascript,Reactjs,我检测到一个组件中的按键,该组件通过一个道具,currentDialog知道应用程序中其他地方当前打开的对话框组件。通常,我可以在嵌套函数中访问此道具,但在使用useCallback时,这似乎是不可能的: export const AllAreaNav = (props) => { console.log('AllAreaNav / props.currentDialog: ', props.currentDialog); // displays correct dialog
useCallback
时,这似乎是不可能的:
export const AllAreaNav = (props) => {
console.log('AllAreaNav / props.currentDialog: ', props.currentDialog); // displays correct dialog
const handleKeyPress = useCallback((event) => {
console.log('AllAreaNav / handleKeyPress / props.currentDialog: ', props.currentDialog); // displays undefined
if(event.keyCode === 70) {
//Do whatever when F is pressed
console.log("F key pressed");
if (props.currentDialog == "DialogSearchBar") {
// Take action based on DialogSearchBar being active
} else {
// Take action based on DialogSearchBar NOT being active
}
}
}, []);
useEffect(() => {
// Listener for keypresses
document.addEventListener("keydown", handleKeyPress, false);
return () => {
document.removeEventListener("keydown", handleKeyPress, false);
};
}, []);
return (
{jsxElements}
)
};
所以现在我有点不确定是否有一种直接的方法将其作为参数传递——假设这是下一步。通过研究,我认为可以在事件旁边添加另一个参数?这应该按照我的意愿进行:
const handleKeyPress = useCallback((event, currentDialog) => {
但是,我不完全确定最初如何将其传递给函数。如果我将侦听器修改为:
document.addEventListener("keydown", handleKeyPress(event, props.currentDialog, false);
我不确定这是否正确,也不确定在此上下文中以
handleKeyPress
默认为参数的方式定义事件的确切位置。您似乎试图通过参数化回调来解决问题,但上下文中没有事件。为了参数化事件并将其置于上下文中,必须在currentDialog
参数上创建一个闭包
您可以尝试以下解决方案:
/**
* move callback definition outside the component
* and create a closure on currentDialog (function returning a function)
*/
const handleKeyPress = (currentDialog) => (event) => {
if (event.keyCode === 70) {
//Do whatever when F is pressed
console.log("F key pressed");
if (currentDialog == "DialogSearchBar") {
// Take action based on DialogSearchBar being active
} else {
// Take action based on DialogSearchBar NOT being active
}
}
};
export const AllAreaNav = (props) => {
console.log("AllAreaNav / props.currentDialog: ", props.currentDialog); // displays correct dialog
useEffect(() => {
// Listener for keypresses
const listener = handleKeyPress(props.currentDialog); // use closure to create a callback closured on currentDialog value
document.addEventListener(
"keydown",
listener,
false
);
return () => {
document.removeEventListener(
"keydown",
listener,
false
);
};
}, [handleKeyPress, props.currentDialog]); // pass callback and currentDialog value to dependency array
return { jsxElements };
};
当我将
props.currentDialog
放在两个依赖项数组中时,它会按预期工作。在props.currentDialog==“DialogSearchBar”
上有闭包。。。由于是空的[]
,IDE中应该有一个警告,请检查它的内容。