簡體   English   中英

如何將任何匿名 function 傳遞給 ref 並在其他反應組件中使用它?

[英]How to pass any anonymous function to ref and use that in other react component?

我有 3 個功能組件,我想通過useRef傳遞和操作數據。
我正在將此onClose方法添加到我的一個組件中的current屬性。

const onClose = () => {
    setButtonColor(buttonColor);
};

ref.current = {
    clearSwitchStateOnClose: onClose,  
};

我在另一個組件中調用該方法。

ref.current.clearSwitchStateOnClose();

我收到此錯誤,

Uncaught TypeError: ref.current.clearSwitchStateOnClose is not a function

我正在調用此方法ref.current.clearSwitchStateOnClose(); 但同時我也在改變ref 我猜這是導致問題的原因。
是這樣的,

ref.current = {
    showModal: false,
    modalResponse: null,
};
ref.current.clearSwitchStateOnClose();

這樣做之后,它工作正常。

ref.current.clearSwitchStateOnClose();
ref.current = {
    showModal: false,
    modalResponse: null,
};

很抱歉沒有分享這種情況的整個場景。

暫無
暫無

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

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