typescript - 通过打字稿中的动态键字符串访问反应原生样式表成员
问题描述
我有这个样式表:
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];
// ...
}
推荐阅读
- reporting-services - SSRS 请求失败,HTTP 状态 502:不可解析
- html - 多行选择 - 从其他选择中删除选定的选项
- php - 查询捕获时间戳 0000-00-00 00:00:00
- xcode - 添加 cocoapods 依赖项后,Fastlane 健身房失败
- laravel - Laravel 服务无法通过 LAN 访问除主页(索引)外
- node.js - powershell和cmd之间的文件大小不同
- php - 为什么我的 php 类在 ajax 调用后不工作
- rest - Clockify API:按项目分组报告并按任务汇总
- python - 在数据框python中复制行
- jmeter - 在 Jmeter 中,我想同时访问 1000 个用户的 1000 个不同的 URL(每个用户同时访问一个 URL)