How to pass props to a styled component in emotion? Using TypeScript

时间:2019-04-16 22:33:25

标签: reactjs typescript styled-components emotion css-in-js

I am using styled by emotion at:

import styled from '@emotion/styled'

I am trying to pass props to a styled component like the guide mentions:

https://emotion.sh/docs/styled

It doesn't work for some reason. I use TypeScript as well. I pass props to my styled component called StyleWrapper here:

const ex: React.FunctionComponent<exProps> = props => {
  return (
    <StyleWrapper someNumber = {props.someNumber}
...
    </StyleWrapper >
  )
}

and in StyleWrapper:

const ToolsHeaderColumn = styled.div`
  padding-top: ${props => props.someNumber };
`

What I get is an error in compilation:

"Property 'someNumber ' does not exist on type 
'Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, 
HTMLDivElement>, "children" | "style" | "title" | 
"color" | "hidden" | "defaultChecked" | "defaultValue" |     "suppressContentEditableWarning" | ... 243 more ... 
| "css"> & { ...; }'.ts(2339)
"

1 个答案:

答案 0 :(得分:1)

by https://github.com/emotion-js/emotion/blob/master/docs/typescript.md this docs, you can make it like:

type ToolsHeaderProps = {
  someNumber: number
}
const ToolsHeaderColumn = styled('div')`
  padding-top: ${(props: ToolsHearderProps) => props.someNumber };
`

if you're using typescript 2.9+, you can use this:

const ToolsHeaderColumn = styled.div<ToolsHearderProps>`
  padding-top: ${(props: ToolsHearderProps) => props.someNumber};
`