0

({ title, subTitle, image })所有 3 都默认为anytype 并且我应该能够将它们设置为 astring 除非有更具体的类型将图像的类型设置为 a URL?我只是使用 Expo 中的默认选项卡模板。它确实使用了TypeScript。 我可能更喜欢将它们设置为inline,但也不反对尝试接口。我认为这只是冒号字符串

: string

但我必须在语法中遗漏一些东西,因为到目前为止它并不喜欢那样。

import React, { FC } from 'react'
import { ImageBackground, StyleSheet, Text, View } from 'react-native'

import colors from '../constants/Colors'
import AppText from './AppText'

// interface AppCardProps {
//   title: string;
//   subTitle: string;
//   image: string;
// }


export default function AppCard({ title, subTitle, image }) {
  return (
    <View style={styles.card}>
      <ImageBackground
        style={styles.image}
        source={image} />
      <View style={styles.detailsContainer}>
        <AppText style={styles.title}>{title}</AppText>
        <AppText style={styles.subTitle}>{subTitle}</AppText>
      </View>
    </View>
  )
}

const styles = StyleSheet.create({
  card: {
    borderRadius: 15,
    backgroundColor: colors.white,
    marginBottom: 20,
    overflow: "hidden",
    // width: 360,
    width: "90%",

  },
  detailsContainer: {
    padding: 20,
  },
  image: {
    // width: 360,
    // width: "100%",
    height: 200,
    // resizeMode: "cover",
    justifyContent: "center",
  },
  subTitle: {
    color: colors.secondary,
    fontWeight: "bold",
  },
  title: {
    marginBottom: 7,
  },
})

在此处输入图像描述

在此处输入图像描述

4

2 回答 2

1

这不是特定于 React Native,而是一般的 TypeScript。

interface AppCardProps {
  title: string;
  subTitle: string;
  image: string;
}

export default function AppCard({ title, subTitle, image }: AppCardProps) {
  // ...
}

或使用React.FC类型

import React from 'react';

interface AppCardProps {
  title: string;
  subTitle: string;
  image: string;
}

const AppCard: React.FC<AppCardProps> = ({ title, subTitle, image }) => {
  // ...
}

export default AppCard;
于 2021-05-15T03:56:27.230 回答
1

这是您可以想象的另一种方式。我实际上更喜欢这种方式,您只需将道具称为道具,而不是进入解构赋值语法,将字段剥离。我觉得让你的组件实际引用 props.title 和 props.subTitle 等是有好处的。当我必须重构 props 并且我不想将它们与其他变量或具有相似名称的 useState 变量混淆时,它也很有帮助。 . 让它们都被称为“props.title”让我知道我肯定会打到通过属性来的标题。

而且,作为附带的好处,当您这样做时,很容易看到 props 变量具有您定义的属性形状。

interface AppCardProps {
  title: string;
  subTitle: string;
  image: string;
}

export default function AppCard(props: AppCardProps) {
  // ...
}
于 2021-05-15T04:27:40.760 回答