簡體   English   中英

React & Typescript 如何從孩子到父母獲得 onClick 道具

[英]React & Typescript how get onClick prop from child to parent

我正在使用反應和 typescript。

我想知道如何使用道具將事件從父母傳遞給孩子。

例子也是如此

父.tsx

const ParentComponent: React.FC<ParentProps> = (props) =>  {
   const [activeItem, setActiveItem] = useState("");

   const getActiveItem = (e: React.MouseEvent, title: string) => {
      setActiveItem(title)
   };

   return (
      <ChildComponent activeItem={activeItem} clickHandler={(e) => getActiveItem(e, 'TITLE')} /> 
   )
}

孩子.tsx

interface ChildProps {
  activeItem: string;
  clickHandler: () => any;
}


const ChildComponent: React.FC<ChildProps> = (props) =>  {
   return (
      <button onClick={props.clickHandler} /> {props.activeItem} </button>
   )
}

在父組件上,我在 clickHandler 上遇到錯誤:

Type '(e: any) => void' is not assignable to type '() => void'.ts(2322)

點擊處理程序的類型應該是這樣的:

interface ChildProps {
  activeItem: string;
  clickHandler: (e:  React.MouseEvent<HTMLButtonElement>) => void;
}

您不應使用any作為參數的類型,因為單擊事件處理程序接受Event作為參數。

在你的孩子道具中,你給類型點擊處理程序clickHandler: () => any; ,它不期望任何參數。

但是當你在父組件中給function時,你給e作為參數。 所以他們不匹配。

你可以輸入你的 clickHanler: clickHandler: (e: any) => any;

但是您可能應該避免any ,並嘗試: (e: React.MouseEvent) => any

暫無
暫無

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

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