【问题标题】:Using types in Styled Component in Typescript在 Typescript 的样式化组件中使用类型
【发布时间】:2021-09-29 08:02:55
【问题描述】:

所以,我正在使用 React Native,之前从未使用过样式化组件。
当我创建一个没有 SC 的新组件时,例如自定义按钮,我执行以下操作:

import React, { ReactNode } from 'react'
import { TouchableOpacity, TouchableOpacityProps} from 'react-native'

import styles from './styles'

type CustomButtonProps = TouchableOpacityProps & {
  children: ReactNode 
}

const CustomButton = ({ children, ...props }: CustomButtonProps) => {
  return (
    <TouchableOpacity style={styles.container} {...props}>
      {children}
    </TouchableOpacity>
  )
}

export { CustomButton }

这样,当我在其他地方使用我的组件时,我可以传递所有未在我的自定义道具中列出的附加 TouchableOpacity 道具。

我想知道当我使用 Styled Components 以继续使用未列出的道具时,我使用什么类型来替换 TouchableOpacityProps,因为如果我使用 TouchableOpacityProps,它会告诉我一个错误类型不匹配:

import React, { ReactNode } from 'react'

import { StyledTouchableOpacity } from './styles'

type CustomButtonProps = ??? & {
  children: ReactNode 
}

const CustomButton = ({ children, ...props }: CustomButtonProps) => {
  return (
    <StyledTouchableOpacity {...props}>
      {children}
    </StyledTouchableOpacity>
  )
}

export { CustomButton }

谢谢你:)

【问题讨论】:

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


    【解决方案1】:

    你的道具是正确的。我认为您使用的是styled.TouchableOpacity,其中TouchableOpacity 由样式组件提供,它会提示您错误,因为它与react-nativeTouchableOpacity 不兼容

    所以给 styled 提供 react-native TouchableOpacity 可以解决类型问题:

    import { TouchableOpacity, TouchableOpacityProps} from 'react-native'
    
    const StyledTouchableOpacity = styled(TouchableOpacity)`
      ...
    `
    

    完整代码:

    import React, { ReactNode } from 'react'
    import { TouchableOpacity, TouchableOpacityProps} from 'react-native'
    import styled from 'styled-components/native';
    
    const StyledTouchableOpacity = styled(TouchableOpacity)`
      padding-vertical: 16px;
      padding-horizontal: 24px;
    `;
    
    type CustomButtonProps = TouchableOpacityProps & {
        children: ReactNode 
    }
    
    const CustomButton = ({ children, ...props }: CustomButtonProps) => {
      return (
        <StyledTouchableOpacity {...props}>
          {children}
        </StyledTouchableOpacity>
      )
    }
    
    export { CustomButton }
    

    【讨论】:

      猜你喜欢
      • 2020-11-05
      • 2019-10-27
      • 2020-07-16
      • 2019-05-09
      • 2019-11-12
      • 2019-04-13
      • 2012-10-03
      • 2021-04-13
      • 2019-07-29
      相关资源
      最近更新 更多