reactjs - გამორთული props-ის მიანიჭება react-bootstrap კომპონენტს შეუძლებელია
მე დავამონტაჟე react-bootstrap და მინდა გავაკონტროლო დეფოლტური ღილაკები ჩემს პროექტში, რათა უმეტეს ღილაკზე უბრალოდ შევძლო დაწერა <Button> ყოველგვარი variant ოფციის გარეშე.
import * as bs from "react-bootstrap";
export const Button: bs.Button = ({
variant = "outline-secondary",
...props
}) => {
return <bs.Button variant={variant} {...props} />;
};
ეს იწვევს შემდეგ შეცდომას.
TypeScript-ის შეცდომა /path/to/MyComponent.tsx(11,11)-ში:
ტიპი '{ variant: string; } & Pick<PropsWithChildren<ReplaceProps<As, BsPrefixProps & ButtonProps>>, "slot" | ... 262 სხვა ... | Exclude<...>>' არ შეიძლება დაინიშნოს ტიპისთვის 'IntrinsicAttributes & Pick<ComponentPropsWithRef, Exclude<keyof ComponentPropsWithRef, "slot" | ... 262 სხვა ... | "onTransitionEndCapture">> & BsPrefixProps<...> & ButtonProps & {. ..; }'.
ტიპი '{ variant: string; } & Pick<PropsWithChildren<ReplaceProps<As, BsPrefixProps & ButtonProps>>, "slot" | ... 262 მეტი ... | Exclude<...>>' არ აღირიცხება ტიპისთვის 'Pick<ComponentPropsWithRef, Exclude<keyof ComponentPropsWithRef, "slot" | "style" | "title" | "as" | "bsPrefix" | ... 258 მეტი ... | "onTransitionEndCapture">>'. TS2322
თუ მე დავწერდი გაყოფის გარეშე, somehow მუშაობს.
export const Button: bs.Button = (props) => {
return (
<bs.Button {...props} variant={props.variant || "outline-secondary"} />
);
};
რატომ არ მუშაობს პირველი? რა ჩამოვარდა props-დან?
განახლება
ვერსიები: TypeScript 4.0.2, React 16.13.1, React Bootstrap 1.3.0
პასუხი #1
თქვენ თითქმის იქ ხართ.
თქვენი კოდი არ მუშაობს, რადგან თქვენ არ გაცხადებთ props-ის ტიპს, ასე რომ, თქვენ უბრალოდ უნდა გააკეთოთ შემდეგი:
const ButtonX: bs.Button = ({
variant = "outline-secondary",
...props
// Here´s the secret - a set props as bootstrap ButtonProps type
}: bs.ButtonProps) => {
return <bs.Button variant={variant} {...props} />;
};
