繁体   English   中英

使用 prop 作为 typescript 的样式索引

[英]Use prop as style index with typescript

我目前正在构建一个具有道具的组件,并希望将道具用作 styles 的索引,但出现 typescript 错误:

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ success: { color: string; }; 警告:{ 颜色:字符串; }; 错误:{ 颜色:字符串; }; }'。 在类型 '{ success: { color: string; 上找不到参数类型为 'string' 的索引签名 }; 警告:{ 颜色:字符串; }; 错误:{ 颜色:字符串; }; }'.ts(7053)

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

type InfoBoxProps = {
  text: string
  context: string
}

const InfoBox: React.FC<InfoBoxProps> = ({ text, context }) => {
  return (
    <View>
      <Text style={styles[context]}>{text}</Text>
    </View>
  )
}

const styles = StyleSheet.create({
  success: {
    color: 'green'
  },
  warning: {
    color: 'yellow'
  },
  error: {
    color: 'red'
  }
})

export default InfoBox

尝试将context定义为:

type InfoBoxProps = {
  text: string
  context: keyof typeof styles
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM