【发布时间】:2021-11-20 13:45:41
【问题描述】:
所以我试图通过让从样式表中选择的样式取决于通过属性传入的字符串来使该组件具有动态分配的样式
export type MyComponentProps = {
styleName: string;
}
const MyComponent = (props: MyComponentProps) => {
const { styleName } = props;
return (
<View
style={[
styles['container'],
styles[`view${styleName}`],
]}>
<Text
style={[
styles['text'],
styles[`text${styleName}`],
]}>
Hello World
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
width: '100%',
alignItems: 'center',
},
viewDark: {
backgroundColor: 'black',
},
viewLight: {
borderColor: 'white',
},
text: {
fontWeight: 'bold',
},
textDark: {
color: 'white',
},
textLight: {
color: 'black',
},
}
但这会引发错误
元素隐式具有“任何”类型,因为“视图${any}”类型的表达式不能用于索引类型“{容器:{宽度:字符串;对齐项目:“中心”; }; viewDark:{背景颜色:字符串; }; viewLight:{背景颜色:字符串; };文本: { ...; };文本黑暗:{ ...; };文本灯:{ ...; }; }'。
我试图避免任何样式本身通过道具进入,我看到这是很多推荐的东西
我也知道看到styles['container']而不是styles.container可能会伤害你的眼睛,但我只是想尽可能清楚地说明我的目标是什么,所以让${styleName}成为这两种情况之间的唯一区别会有所帮助
【问题讨论】: