简体   繁体   中英

How to pass a handler to onClick with Typescript and material UI

I want to pass a function that returns another function to material UI's onTouchTap event:

<IconButton
   onTouchTap={onObjectClick(object)}
   style={iconButtonStyle} >
      <img alt={customer.name} className="object-img" src={object.avatarSrc} />
</IconButton>

But I keep running into the following error:

Type '{ onTouchTap: Function; style: CSSProperties; tooltip: string; children: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<IconButton> & Readonly<{ children?: ReactNode; }> ...'.

If I just pass a function, the click event gets fired and everything works:

<IconButton
       onTouchTap={onObjectClick}
       style={iconButtonStyle} >
          <img alt={customer.name} className="object-img" src={object.avatarSrc} />
    </IconButton>

However, the function runs with an event passed, which does not help me. I need to instead pass an object with data in it. Does anyone know how to set a function that returns a function, or a handler to onTouchTap or an onClick event in react using typescript?

To pass arguments to onTouchTap you need to pass an arrow function and call the function with the desired arguments, like so:

<IconButton
   onTouchTap={() => onObjectClick(object)}
   style={iconButtonStyle} >
      <img alt={customer.name} className="object-img" src={object.avatarSrc} />
</IconButton>

The reason for this is because onTouchTap and other properties like it take a function object , not a function call . By doing this you're passing an anonymous function (the arrow function) that calls your function with the desired arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM