首页 > 解决方案 > 通过打字稿中的动态键字符串访问反应原生样式表成员

问题描述

我有这个样式表:

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 推向正确的方向并让它快乐?

标签: typescriptreact-native

解决方案


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

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];

  // ...
}

推荐阅读