添加onclick监听器reactjs

我想点击按钮时添加回调功能 .

我的代码:

export enum PAYMENT_METHOD {
  online,
  offline,
}

interface Props {
  paymentMethod: PAYMENT_METHOD;
  togglePaymentMethod: (paymentMethod: PAYMENT_METHOD) => void;
}

const AmountToPayModal = (props: Props) => (
  <Container>
    <SectionLabel>
  2.&nbsp;
  <FormattedMessage id="SE-206.Section2.Title" />
</SectionLabel>
<PaymentBox>
      <PaymentButtonDeselected >
        <FormattedMessage id="SE-206.Section2.OnlinePayment" />
      </PaymentButtonDeselected>
      <PaymentButtonSelected onClick={props.togglePaymentMethod(PAYMENT_METHOD.online)}>
        <FormattedMessage id="SE-206.Section2.OfflinePayment" />
      </PaymentButtonSelected>
    </div>
</PaymentBox>
</Container>
    );

[ts]输入'{onClick:void;儿童:元素; }'不能赋值为'IntrinsicAttributes&IntrinsicClassAttributes,any >>' . 属性'onClick'的类型不兼容 . 类型'void'不能分配给'EventHandler> |类型未定义” .

我正在使用TypeScript .

回答(1)

2 years ago

onClick 处理程序中,您没有传递函数,而是调用函数 . 您的函数将被调用 when the AmountToPayModal is called (during render), not when the user makes a click. 并且该函数返回 void ,因此TypeScript推断(正确地)您将 void 分配给事件处理程序 .

我认为你真正想要做的是:

<PaymentButtonSelected onClick={() => props.togglePaymentMethod(PAYMENT_METHOD.online)}>

现在,您正在为处理程序分配一个函数,当用户单击该元素时,将正确调用您的函数