简体   繁体   中英

Additional Arguments to Styled Components in React with Typescript

I have a styled component I need to reuse. It looks like this:

export const FormFooter = styled.div(
  ({ theme }) => `
  padding: ${theme.spacing(3)}px;
  border-top: 1px solid ${theme.palette.lighterGray};
  position: sticky;
  width: 100%;
`,
)

This component is used elsewhere in our codebase and but there's one application where I need it to behave slightly differently. Specifically, I need position to be absolute and bottom to be '0'.

I want to be able to pass additional arguments to this component and set default values for them. Is there a way to do that?

I'm looking for something like:

export const FormFooter = styled.div<{position?: string, bottom?: string}>(
  ({ theme }) => `
  padding: ${theme.spacing(3)}px;
  border-top: 1px solid ${theme.palette.lighterGray};
  position: ${position ? position : 'sticky'};
  bottom: ${bottom ? bottom : 'inherit'}
  width: 100%;
`,
)

But this gives me a typescript error stating that position and bottom are not defined.

You have just added type annotations, and not really defined the new parameters in the function signature. Here is a better way to do this:

import styled from "styled-components";

export type FormFooterProps = {
  theme: any, //Use appropriate type
  position?: string,
  bottom?: string;
}
export const FormFooter = styled.div<FormFooterProps>(
  ({ theme, position = "sticky", bottom = "inherit" }) => `
  padding: ${theme.spacing(3)}px;
  border-top: 1px solid ${theme.palette.lighterGray};
  position: ${position};
  bottom: ${bottom}
  width: 100%;
`
);

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