React & Typescript 如何从子级到父级获取 onClick 属性

ciz*_*z30 3 javascript typescript reactjs

我正在使用反应和打字稿。

我想知道如何使用道具将事件从父母传递给孩子。

例子也是如此

父级.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')} /> 
   )
}
Run Code Online (Sandbox Code Playgroud)

孩子.tsx

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


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

在父组件上,我在 clickHandler 上遇到错误:

Type '(e: any) => void' is not assignable to type '() => void'.ts(2322)
Run Code Online (Sandbox Code Playgroud)

wen*_*jun 7

单击处理程序的输入应如下所示:

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

您不应该使用any作为参数的类型,因为单击事件处理程序接受Event作为参数。