如何将 onClick 作为组件库中的参数?

How to take onClick as an argument in component library?

我希望在使用自定义按钮组件时能够触发一个功能,直接添加onClick是行不通的。

Button.tsx

import React from 'react';

export interface ButtonProps {
  rounded: 'small' | 'medium' | 'full';
  label: string;
  icon?: string;
  size: 'small' | 'medium' | 'full';
  type: 'outline' | 'quiet' | 'fill';
  disabled?: boolean;
  variant: 'accent' | 'primary' | 'secondary';
}

export const Button = ({
  rounded,
  label,
  icon,
  size,
  type,
  disabled,
  variant,
}: ButtonProps) => {
  const disabledStyles = 'bg-gray-200 cursor-not-allowed';
  const sizeSmall = 'px-4 py-2';
  const sizeMedium = 'px-6 py-3';
  const sizeLarge = 'px-8 py-4';
  return (
    <>
        <button
        type="button"
        className={`rounded focus:outline-none focus:ring-[3px] inline-flex justify-center
          ${disabled === true && disabledStyles}
          ${size?.toLowerCase() === 'small' && sizeSmall}
          ${size?.toLowerCase() === 'medium' && sizeMedium}
          ${size?.toLowerCase() === 'large' && sizeLarge}`}
        >
          ${label}
        </button>
    </>
  );
};

我想在单击按钮时触发 myFunction

import {Button} from myLibraryName;

const myFunction = () => {
    console.log('function passed')
}

return <Button [arguments] />

您需要将 onClick 作为按钮属性传递,然后在 Button 组件中您需要将其添加到 ButtonProps 界面。然后简单地将它传递给渲染函数内的 button 元素。

您的 Button.tsx 将如下所示:

import React from 'react';

export interface ButtonProps {
  rounded: 'small' | 'medium' | 'full';
  label: string;
  icon?: string;
  size: 'small' | 'medium' | 'full';
  type: 'outline' | 'quiet' | 'fill';
  disabled?: boolean;
  variant: 'accent' | 'primary' | 'secondary';
  onClick: () => void;
}

export const Button = ({
  rounded,
  label,
  icon,
  size,
  type,
  disabled,
  variant,
  onClick,
}: ButtonProps) => {
  const disabledStyles = 'bg-gray-200 cursor-not-allowed';
  const sizeSmall = 'px-4 py-2';
  const sizeMedium = 'px-6 py-3';
  const sizeLarge = 'px-8 py-4';
  return (
    <>
        <button
        onClick={onClick}
        type="button"
        className={`rounded focus:outline-none focus:ring-[3px] inline-flex justify-center
          ${disabled === true && disabledStyles}
          ${size?.toLowerCase() === 'small' && sizeSmall}
          ${size?.toLowerCase() === 'medium' && sizeMedium}
          ${size?.toLowerCase() === 'large' && sizeLarge}`}
        >
          ${label}
        </button>
    </>
  );
};

函数将像这样传递下去:

import {Button} from myLibraryName;

const myFunction = () => {
    console.log('function passed')
}

return <Button ...arguments onClick={myFunction}  />