简体   繁体   English

如何使用Typescript和材料UI将处理程序传递给onClick

[英]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: 我想传递一个函数,该函数将另一个函数返回给用户界面的onTouchTap事件:

<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: 如果我只是传递一个函数,则会触发click事件,并且一切正常:

<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. 但是,该函数在传递event运行,这对我没有帮助。 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? 有谁知道如何设置返回函数的函数或onTouchTap的处理程序或使用TypeScript进行响应的onClick事件?

To pass arguments to onTouchTap you need to pass an arrow function and call the function with the desired arguments, like so: 要将参数传递给onTouchTap您需要传递一个箭头函数并使用所需的参数调用该函数,如下所示:

<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 . 这样做的原因是因为onTouchTap和其他类似的属性带有函数对象 ,而不是函数调用 By doing this you're passing an anonymous function (the arrow function) that calls your function with the desired arguments. 通过这样做,您传递了一个匿名函数(箭头函数),该函数使用所需的参数调用函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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