Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - 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.

question from:https://stackoverflow.com/questions/65948054/additional-arguments-to-styled-components-in-react-with-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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%;
`
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...