我希望能夠在使用自定義按鈕組件時觸發功能,直接添加 onClick 不起作用。
按鈕.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] />
uj5u.com熱心網友回復:
您需要將 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} />
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398174.html
