我有这个样式表:
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/