简体   繁体   中英

Typescript React.ComponentProps is not getting the props

在此处输入图像描述

boxProp is not found in the props .

Library versions:

├─ react@16.13.1

└─ styled-components@5.2.1

Edit: https://codesandbox.io/s/jovial-germain-qunlz

This won't work because you aren't actually passing any props to your Box component, all that first line is doing is annotating WHICH props your Box component can consume - so React has no context of which props to extract when using the ComponentProps method.

Seeing as you are annotating the prop type yourself, an easy fix for this would be to do the following:

type BoxProps = { boxProp: boolean }

const Box = styled('div')<BoxProps>

const MyBox: React.FC<BoxProps> = ({ boxProp }) => {
  return (
    <Box boxProp={boxProp} />
  )
}

Let me know if that helps!

Here goes my last attemp to solve this:

type OwnProps = { boxProps?: boolean };

const Box = styled.div<OwnProps>``;

type CustomBoxProps = StyledComponentProps<'div', DefaultTheme, OwnProps, never>;

export const MyBox: React.FC<CustomBoxProps> = (props) => {
  return (<Box {...props} />);
};

unfortunately StyledComponentProps has to be used. React.ComponentProps doesn't work well with styled-components interface. Definitely something wrong on their side.

Please let me know if that solves your problems, it should

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM