簡體   English   中英

Javascript 點擊事件監聽器與反應 function

[英]Javascript click event listener with react function

我想創建一個自定義掛鈎,在其中我將單擊事件偵聽器添加到 DOM 元素,該元素調用在使用 state 變量的 React 組件中定義的 function。

我添加了事件監聽器,但是當我調用 function 時,它沒有反映任何 state 更改,它始終采用初始 state 值。

const useCustomHook = (functionDefinedInComponent) => {
  // logic to get the dom element
  element.addEventListener('click', () => functionDefinedInComponent(item)); 
};

const CustomComponent = () => {
  const [state, setState] = useState(...);

  const customFunction = (item) => {
    setState(...); // change the 'state' variable
    // use item and state to do something
  }

  useCustomHook(customFunction);

  return ...;
}

當我單擊添加了單擊事件的 DOM 元素時, customFunction會觸發初始 state 值。 有沒有辦法解決這個問題?

您可以像這樣使用公共組件:

const ClickableComponent = props => {
    const { title, handleClick, component: Component } = props;
    return (
        <Component onClick={handleClick}>{title}</button>
    )
};

export default ClickableComponent;

你可以像下面這樣使用這個組件:

<ClickableComponent title="your title" handleClick={handleClick} component={<button/> } />

我的意思是這樣的。 您可能還必須將回調 function 包裝在 React.useCallback 中。

const useCustomHook = (functionDefinedInComponent) => {
  React.useEffect(() => {
     // logic to get the dom element
      element.addEventListener('click', () => functionDefinedInComponent()); 
  }, [functionDefinedInComponent])
 
};

你能試試這個,讓我知道你遇到了什么樣的問題。

暫無
暫無

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

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