首页 > 解决方案 > 将函数传递给另一个组件时,onClick 道具不起作用

问题描述

我有一个这样的组件

<CardAvReport
  buttonProps={buttonProps ? { ...buttonProps , small: true,  onClick: () => console.log("hi")} : null}
  onHandlerExample={this.someotherFunction}
  includeLink
  showChildren
  {...rest}
>

这个组件渲染了一个div,这个div包含了一个由onClick触发的按钮。

如果单击,我可以看到 console.log("hi") 被触发。问题是如果我调用这样的函数

<CardAvReport
  buttonProps={buttonProps ? { ...buttonProps , small: true,  onClick: () => this.myFunction} : null}
  onHandlerExample={this.someotherFunction}
  includeLink
  showChildren
  {...rest}
>

它不会工作。

在 CardAvReport 中,buttonprops 最终出现在另一个组件中

<ButtonLink {...buttonProps}>{buttonProps.text}</ButtonLink>

该组件定义为

import * as React from "react";
import Button from "./Button";

export default props => {
  const { link, onClick, children, ...rest } = props;
  let props2 = { onClick };
  if (link) props2["href"] = link;
  if (onClick) props2.onClick = onClick;
  return (
    <a {...props2}>
      <Button {...rest}>{children}</Button>
    </a>
  );
};

我不明白如何调试它,以及为什么一个函数在 onClick 中不起作用。

标签: javascriptreactjs

解决方案


推荐阅读