我创建了具有浅色和深色主题样式的React Native功能组件。
const lightThemeOverrides = StyleSheet.create({ <light_override_styles_here> });
const styles = StyleSheet.create({ <styles_here> });
我正在尝试借助功能在代码中使用它们:
const themedStyles = (key: string) => {
if (props.theme === 'light') {
return { ...styles[key], ...lightThemeOverrides[key] };
} else {
return styles[key];
}
};
我在JSX中使用此功能的方式如下:<View style={themedStyles('popup')}>
但是我的ts linter在抱怨Element implicitly has an 'any' type because type '{ popup: { backgroundColor: string; }; text: { color: string; }; }' has no index signature.
有人知道如何解决此问题吗? 所有提示将不胜感激。
答案 0 :(得分:0)
我当前的解决方案是像这样修改themedStyles
函数:
const themedStyles = (key: 'popup' | 'text'): StyleProp<any> => {
if (props.theme && props.theme === 'light') {
return { ...styles[key], ...lightThemeOverrides[key] };
} else {
return styles[key];
}
};
密钥的类型为'popup' | 'text'
或类似的密钥。在lightThemeOverrides
样式表中包含每个可能的键。
我还将函数的类型设置为StyleProp<any>
,以解决JSX中的其他类型问题。
尽管我不喜欢这种解决方案,因为必须为每个组件更改该功能,但它确实起作用。目前。仍然欢迎任何其他评论:)