admin管理员组

文章数量:1289383

I'm using react & typescript.

I wonder how i can pass event from parent to child with props.

so is example

parent.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')} /> 
   )
}

child.tsx

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


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

and on parent ponent i'm getting error on clickHandler:

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

I'm using react & typescript.

I wonder how i can pass event from parent to child with props.

so is example

parent.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')} /> 
   )
}

child.tsx

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


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

and on parent ponent i'm getting error on clickHandler:

Type '(e: any) => void' is not assignable to type '() => void'.ts(2322)
Share Improve this question asked Apr 28, 2020 at 13:55 ciz30ciz30 4533 gold badges12 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

This is how the typings for the click handler should be:

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

You should not use any as the type for the parameter, as on click event handler accepts Event as the parameter.

In your child prop you give type click handler clickHandler: () => any;, it does not expect any params.

But when you give the function in the parent ponent, you give e as a parameter. So they don't match.

You could type your clickHanler : clickHandler: (e: any) => any;

But you should probably avoid any, and try : (e: React.MouseEvent) => any.

本文标签: javascriptReact amp Typescript how get onClick prop from child to parentStack Overflow