gpt4 book ai didi

javascript - 如何使用 React Hooks 将状态值传递给回调函数

转载 作者:行者123 更新时间:2023-11-30 13:51:54 25 4
gpt4 key购买 nike

正在使用 react-modal 创建面板,一切似乎都运行良好。

但是一旦模态框打开,我需要设置模态框的最高值。我正在使用钩子(Hook),每当我尝试更新值时,就会出错,只能在 React 函数内部调用钩子(Hook)。我尝试了所有可能的方法,但无法解决问题。

期望:- 应调用 OnAfterOpen,并将最新的状态值传递给 pos prop

这是我试过的。

function useTop() {
const [top, setTop] = useState('100px');

useEffect(() => {
const handleResize = () => {
const hasRefClientHeight = contentRef.current && contentRef.current.clientHeight;
hasRefClientHeight < window.innerHeight ? setTop(`calc(100% - ${hasRefClientHeight}px)`) : setTop('100px');
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);

return top;
}

const Panel = () => {
// const newTop = useTop(); -- This is not working as modal content is not ready. Modal Content will be ready only if `onAfterOpen` triggers.

<Modal pos={useTop} onAfterOpen={useTop}><div ref={contentRef}>Test</div></Modal>
};

最佳答案

的确,钩子(Hook)的规则是这样说的:

https://reactjs.org/docs/hooks-rules.html

Only Call Hooks at the Top Level

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)

React 必须确保在每个渲染周期中以完全相同的顺序调用 Hook 。

似乎 Modal 只会在挂载(打开)后调用 useTop,即它可能会跳过第一次渲染,违反了钩子(Hook)规则并弄乱了订单。

你可以尝试一件事:

为您的 useTop Hook 传递 ref 并在其中处理它。如果为 null,则不执行任何操作,如果已挂载,则附加监听器并返回清理函数。

const Panel = () => {
const newTop = useTop(contentRef);
<Modal pos={newTop} onAfterOpen={null}><div ref={contentRef}>Test</div></Modal>
};

关于javascript - 如何使用 React Hooks 将状态值传递给回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58072279/

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