样式化组件和 TypeScript:没有与此调用匹配的重载

时间:2021-02-23 13:54:02

标签: reactjs typescript react-native typeerror styled-components

我是 Style Components 的新手,我正在尝试使用 React Native 构建一个天气应用程序。我通常会使用 CSS 模块,但似乎这不是移动开发的选项。

代码如下:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1

这是错误的屏幕截图:

overload error

这是 Theme.tsx

import ThemeModel from 'models/ThemeModel'
import React, { PureComponent } from 'react'
import styled from 'styled-components/native'

interface HomeScreenComponentInterface {
  theme?: ThemeModel
  getWeatherData: () => void;
  isLoading: boolean | null;
}

class HomeScreenComponent extends PureComponent<HomeScreenComponentInterface> {
  componentDidMount() {
    const { getWeatherData } = this.props

    getWeatherData()
  }

  render() {
    const Container = styled.View`
    padding: 20px 0;
  `
    const HeaderText = styled.Text`
    color: ${(props: HomeScreenComponentInterface) => props.theme && props.theme.colors.lightBlue};
    font-size: ${(props: HomeScreenComponentInterface) => props.theme && props.theme.fontSizes.xLarge};
    font-weight: 500;
  `
    return (
      <Container>
        <HeaderText>Weather App</HeaderText>
      </Container>
    )
  }
}

我相信我只需要将主题道具传递给这个组件,但我不知道该怎么做..

必须感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

 const HeaderText = styled.Text`
     color: ${({ theme }) => theme.colors.lightBlue};
 `;

您不必在道具界面 (HomeScreenComponentInterface) 中包含主题的类型。 ThemeProvider 为其子项中的所有样式组件提供主题。 Typescript 抛出该错误是因为您告诉 HeaderText 样式的组件期待 isLoading 和 getWeatherData 道具。这些道具不是渲染样式组件所必需的。

答案 1 :(得分:0)

 const HeaderText = styled.Text<HomeScreenComponentInterface>`// Typescript magic
    color: ${({ theme }) => theme && theme.colors.lightBlue};
    `

Typescript 无法推断传递给样式化组件的 props 的类型,因此您必须如上明确设置它们。

答案 2 :(得分:0)

interface HomeScreenComponentInterface {
  theme?: ThemeModel          // optional  
  getWeatherData: () => void; // required
  isLoading: boolean | null;  // required
}

没有与此调用匹配的重载 错误发生,因为 <HeaderText> 需要根据您定义的接口所需的属性。将它们设为可选,它应该可以工作。

我遇到了同样的问题。 将接口中定义的道具值更改为可选?为我解决了问题。

错误示例:

interface CustomStyleProps {
     width: number;
     height: number;
};

const CarouselContainer = styled.div<CustomStyleProps>`
   display: flex;
   width: ${props => (props.width || 100) + `px`};
   height: ${props => (props.height || 100) + `px`};
`;
 
return(
     <CarouselContainer/> // Error : No overload matched this call
)

没有错误的例子:

interface CustomStyleProps {
      width?: number;
      height?: number;
};
    
 const CarouselContainer = styled.div<CustomStyleProps>`
     display: flex;
     width: ${props => (props.width || 100) + `px`};
     height: ${props => (props.height || 100) + `px`};
 `;

 return(
     <CarouselContainer/> // No Error
 )