代码之家  ›  专栏  ›  技术社区  ›  Roman Mahotskyi

样式化组件中的道具没有类型

  •  0
  • Roman Mahotskyi  · 技术社区  · 6 年前

    我使用react native+typescript+styled组件(安装了所有@types/*),但道具在“组件”中仍然没有键入内容

    怎么了?

    我希望道具 props: MainThemeInterface 或 props: { mode: string } .

    // button.component.ts
    import { FC } from 'react';
    import styled from 'styled-components/native';
    
    interface ButtonComponentProps {
      title: string;
      onPress: (event: GestureResponderEvent) => void;
    }
    
    const Button = styled.TouchableOpacity`
      border-radius: 5px;
      padding: 11px 16px;
      background: ${props => props};
      align-self: flex-start;
    `;
    
    export const ButtonComponent: FC<ButtonComponentProps> = props => (
      <Button onPress={props.onPress}>{props.title}</Button>
    );
    
    // styled.d.ts file
    import 'styled-components/native';
    import { MainThemeInterface } from './theme.model';
    
    // and extend them!
    declare module 'styled-components' {
      // eslint-disable-next-line @typescript-eslint/no-empty-interface
      export interface DefaultTheme extends MainThemeInterface {}
    }
    
    // theme.model.ts file
    export MainThemeInterface {
       mode: string;
    }
    

    enter image description here enter image description here

    使现代化

    我降级为 "styled-components": "^3.4.9" 打字也开始起作用了。似乎版本中存在问题 ^5.0.0 .

    更新2

    问题在于项目设置内部。在使用重新创建项目之后 expo cli 问题消失了。

    0 回复  |  直到 6 年前
        1
  •  1
  •   Rafael Dias    6 年前

    我也有同样的问题。试图取代

    declare module 'styled-components' {
      // eslint-disable-next-line @typescript-eslint/no-empty-interface
      export interface DefaultTheme extends MainThemeInterface {}
    }
    

    通过

    declare module 'styled-components/native' {
      // eslint-disable-next-line @typescript-eslint/no-empty-interface
      export interface DefaultTheme extends MainThemeInterface {}
    }
    

    问题依然存在。我无法使用样式化组件和类型脚本为react native实现主题化。

        2
  •  0
  •   Emma    6 年前

    我只是想进一步阐述一下我的看法。。您可以尝试将道具界面传递给按钮的样式对象,如下所示

    
    const Button = styled.TouchableOpacity<ButtonComponentProps>`
      border-radius: 5px;
      padding: 11px 16px;
      background: ${props => props};
      align-self: flex-start;
    `;
    

    或

    const Button = styled.TouchableOpacity<{ mode: string }>`
      border-radius: 5px;
      padding: 11px 16px;
      background: ${props => props};
      align-self: flex-start;
    `;
    
    推荐文章