gpt4 book ai didi

javascript - useCallback 不继承父 Prop

转载 作者:行者123 更新时间:2023-12-04 08:36:15 25 4
gpt4 key购买 nike

我正在检测组件中的按键,该组件知道当前通过 Prop 在应用程序的其他地方打开了什么对话框组件, currentDialog .通常我可以在嵌套函数中访问这个 Prop ,但在使用 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 };
};

关于javascript - useCallback 不继承父 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64784457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com