Using styled components with props and typescript

后端 未结 4 1976
眼角桃花
眼角桃花 2021-02-01 20:24

I\'m trying to integrate typescript into our project and so far I stumbled upon one issue with styled-components library

Consider this component

import *         


        
4条回答
  •  伪装坚强ぢ
    2021-02-01 20:46

    This answer is outdated, the most current answer is here: https://stackoverflow.com/a/52045733/1053772

    As far as I can tell there is no official way (yet?) to do this, but you can solve it with a bit of trickery. First, create a withProps.ts file with the following content:

    import * as React from 'react'
    import { ThemedStyledFunction } from 'styled-components'
    
    const withProps = () => (fn: ThemedStyledFunction) =>
        fn as ThemedStyledFunction

    export { withProps }

    Now, inside your .tsx files, use it like this:

    // ... your other imports
    import { withProps } from './withProps'
    
    export interface IconProps {
      onPress: any;
      src: any;
      width: string;
      height: string;
    }
    
    const Icon = withProps()(styled.Image)`
      width: ${(p: IconProps) => p.width};
      height: ${(p: IconProps) => p.height};
    `;
    

    And you should be good to go. It's definitely not ideal and hopefully there will be a way to provide generics to template literals soon in TS, but I guess that for now this is your best option.

    Credit is given where credit is due: I copypasted this from here

提交回复
热议问题