简体   繁体   English

如何将函数作为道具传递给组件并在不使用 React+Typescript 中的箭头符号的情况下调用它们?

[英]How to pass functions as props to components and call them without using arrow notation in React+Typescript?

I have a function, selectMarket() , which I'm passing as a prop to a component, AssetSelectorRow .我有一个 function, selectMarket() ,我将其作为道具传递给组件AssetSelectorRow In the AssetSelectorRow , I'm assigning the function to be called during an onClick event.AssetSelectorRow中,我指定 function 在onClick事件期间被调用。

If I use onClick={selectMarket(asset)} , I get the following error:如果我使用onClick={selectMarket(asset)} ,我会收到以下错误:

Type 'void' is not assignable to type '((event: MouseEvent<HTMLDivElement, MouseEvent>) => void) | undefined'.  TS2322

If I use onClick={() => selectMarket(asset)} , then everything works as intended, but I'd like to avoid this notation as it unnecessarily renders a new callback on each render.如果我使用onClick={() => selectMarket(asset)} ,那么一切都按预期工作,但我想避免这种表示法,因为它不必要地在每次渲染时渲染一个新的回调。 I'm also just curious as to why the former doesn't work.我也很好奇为什么前者不起作用。

const selectMarket = (market: IPositionListItem) => {
  if (
    currentSymbol.base.id !== market.base ||
    currentSymbol.quote.id !== market.counter
  ) {
    setSelectedMarket(market);
  }
};

<AssetSelectorRow
  key={asset.name}
  asset={asset}
  selectMarket={selectMarket}
/>

AssetSelectorRow.js : AssetSelectorRow.js

interface IOwnProps {
  asset: IPositionListItem;
  selectMarket: (asset: IPositionListItem) => void;

export const AssetSelectorRow = memo(({ asset, selectMarket }: IOwnProps) => {
  return (
    <div
      className="bp3-button-group bp3-fill bp3-minimal menu-item-group"
      key={asset.name}
      onClick={selectMarket(asset)}
    >
      Asset
    </div>
  );
});

The error is correct, because the expected signature of the click event handler does not match your actual handler.错误是正确的,因为单击事件处理程序的预期签名与您的实际处理程序不匹配。

You might adjust your function as follows:可以按如下方式调整您的 function:

const selectMarket = (event: MouseEvent<HTMLDivElement, MouseEvent>, market: IPositionListItem) => {
  if (
    currentSymbol.base.id !== market.base ||
    currentSymbol.quote.id !== market.counter
  ) {
    setSelectedMarket(market);
  }
};

but now the problem is:但现在的问题是:

how to pass the second argument (market) to the function?如何将第二个参数(市场)传递给 function?

the onClick event does not do that for you. onClick事件不会为您做到这一点。

Thus, the only way to correctly handle your function is via indirect handler call, as you already figured it out:因此,正确处理 function 的唯一方法是通过间接处理程序调用,正如您已经弄清楚的那样:

onClick={() => selectMarket(asset)}

it works because the signature simply drops the expected argument (event), but that's not in conflict to anything.它之所以有效,是因为签名只是删除了预期的参数(事件),但这与任何事情都不冲突。

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

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