typescript - 如何将 Type 传递给 TypeScript 中的 statelles 组件
问题描述
好吧,我想使用一个组件来呈现不同类型的数据,因为我使用打字稿,我需要传递我的平面列表将使用的数据类型,到目前为止,我只有音乐和播放列表。有没有办法通过父亲传递这些类型?因为我想重用这些组件
用户类型
type userType = {
id: string
name: string
email: string
password: string
}
播放列表类型
type playlistType = {
id: string
name: string
user: userType
}
音乐类型
type musicType = {
id: string
name: string
artist: string
album: string
releaseyear: Date
genre: string
duration: string
user: userType
}
组件
const scrollableView: React.FC<scrollableViewProps> = (props /* There is nothing coming to props yet */) => {
return (
<FlatList <Type of data that cames>
/* The settings for flatlist */
/>
)
}
将调用列表两次的父组件
const Dashboard: React.FC<DashboardScreenProps> = ({navigation}) => {
let {loggedUser} = useContext(UserContext)
let [fetchedData, setFetchedData] = useState<fetchedDataType>({
playlists: [],
musics: []
})
/* Some code here thats not important */
return (
<View style={Style.container}>
<View>
<Text>Playlists</Text>
<ScrollableView /> //The component I would like to pass playlist type
</View>
<View>
<Text>Musics</Text>
<ScrollableView /> //The same component I would like to pass music type
</View>
</View>
)
}
解决方案
您可以使用联合类型。|
运算符基本上是一个forOR
类型。
type scrollableViewProps = {
data: musicType | playlistType
}