Using styled components with props and typescript

后端 未结 4 1977
眼角桃花
眼角桃花 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:43

    I'm struggling through this myself, but I think the problem is that you are using the Props interface inside the styled component. Try creating another interface with just the image props and use that in your styled component:

    import * as React from "react";
    import styled from "styled-components/native";
    import { TouchableOpacity } from "react-native";
    
    // -- types ----------------------------------------------------------------- //
    export interface Props {
      onPress: any;
      src: any;
      width: string;
      height: string;
    }
    
    
    export interface ImageProps {
      src: string;
      width: string;
      height: string;
    }
    
    // -- styling --------------------------------------------------------------- //
    const Icon = styled.Image`
      width: ${(p: ImageProps ) => p.width};
      height: ${(p: ImageProps ) => p.height};
    `;
    
    class TouchableIcon extends React.Component {
      // -- default props ------------------------------------------------------- //
      static defaultProps: Partial = {
        src: null,
        width: "20px",
        height: "20px"
      };
    
      // -- render -------------------------------------------------------------- //
      render() {
        const { onPress, src, width, height } = this.props;
        return (
          
            
          
        );
      }
    }
    
    export default TouchableIcon;
    

    Seems to work but I hate to have to duplicate those interfaces. Hopefully someone else can show the correct way or maybe embedding the ImageProps into Props?

提交回复
热议问题