typescript - 通过 typescript 中的动态键字符串访问 react native 样式表成员

标签 typescript react-native

我有这个样式表:

const styles = StyleSheet.create({
  primary: {},
  secondary: {},
})

我想使用动态组合的字符串访问键。

<View style={styles[props.type]}/>

这就是 TS 提示的时候(但代码运行得很好):

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ primary: { }; secondary: { }'.
  No index signature with a parameter of type 'string' was found on type '...'.ts(7053)

我怎样才能将 TS 推向正确的方向并使其高兴?

最佳答案

这是最小的精简工作示例:

import { StyleSheet } from "react-native";

type Props = {
    type: 'primary' | 'secondary'
}

const styles = StyleSheet.create({
    primary: {},
    secondary: {}
});

const Component: React.FC<Props> = ({ type }) => {
  const style = styles[props.type];

  // ...
}

关于typescript - 通过 typescript 中的动态键字符串访问 react native 样式表成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62068006/

相关文章:

css - 如何在 flexbox 容器中混合固定大小和动态大小的元素?

javascript - Typescript TS2339 类型上不存在属性 - 类声明

typescript - 使用 TypeScript,有没有一种方法可以定义一个对象,其中每个键都是相同类型,同时保留使用哪些键的信息?

reactjs - 类型 'string | null' 不可分配给类型 'string'

angular - 失败 : script timeout: result was not received in 11 seconds From: Task: Protractor. waitForAngular() - 定位器 : By(css selector, #my-btn)

ios - RCTBatchedBridge 已弃用,将在未来的 React Native 版本中删除

amazon-web-services - react-native-google-signin 与 AWS Cognito

android - 'gradlew.bat' 不被识别为内部或外部命令, native react

使用函数解析的 Typescript 回调参数

facebook - 如何在 React Native 中使用 Facebook Messenger 对话框?