0

我是 React 和 TypeScript 的新手。

我想做一个简单的函数来触发console.log();我已经阅读了一些教程但并不真正理解。

我已经按照教程创建了一个界面:

interface ClickHandlerProps {
  onClick; (event: React.SyntheticEvent<Event>, buttonType: string) => void
}

在返回函数中我有:

<Button
  onClick={(e) => props.onClick(e, "button1")}
>

但是教程到此结束。我真的不知道如何触发console.log()。

我知道这有点含糊,但是有人可以帮助我并指出正确的方向吗?

完整代码:

import React from 'react';
import { Button, Grid } from '@material-ui/core';

interface ClickHandlerProps {
  onClick; (event: React.SyntheticEvent<Event>, buttonType: string) => void
}

const ActionButtons = ({ onClick }: EventHandlerProps) => {

  return (
    <>
      <Grid container spacing={3}>
        <Grid item xs={4}>
          <Button onClick={(e) => props.onClick(e, "button1")} >
            Button 1
          </Button>
        </Grid>
        <Grid item xs={4}>
          <Button onClick={(e) => props.onClick(e, "button2")} >
            Button 2
          </Button>
        </Grid>
      </Grid>
    </>
  );
};

export default ActionButtons;

在 index.tsx 上

import ActionButtons from './ActionButtons';
export default ActionButtons;
4

2 回答 2

1

您在这里打错了:您必须使用冒号将属性名称与其类型分开。

interface ClickHandlerProps {
  onClick: (event: React.SyntheticEvent<Event>, buttonType: string) => void
}
于 2020-04-27T02:39:29.217 回答
1

现在您可以ActionButtons像这样使用您的组件:

import React, {SyntheticEvent} from 'react';

const MyComponent = (props) => {
  const clickHandler = (evt: SyntheticEvent<Event>, btnType: string) => {
    console.log(`Button clicked: ${btnType}`
  };

  return <ActionButtons onClick={clickHandler}></ActionButtons>
}

export default MyComponent;

请注意,您将clickHandler函数传递给onClick输入,因此内部的任何点击ActionButtons都会调用clickHandler.

ActionButtons顺便说一句,示例组件似乎有一些错误:

const ActionButtons = ({ onClick }: EventHandlerProps) => {
  return (
    <>
      <Grid container spacing={3}>
        <Grid item xs={4}>
          <Button onClick={(e) => onClick(e, "button1")} >
            Button 1
          </Button>
        </Grid>
        <Grid item xs={4}>
          <Button onClick={(e) => onClick(e, "button2")} >
            Button 2
          </Button>
        </Grid>
      </Grid>
    </>
  );
};

export default ActionButtons;
于 2020-04-27T02:47:28.600 回答