无法读取React Native风格的undefined属性

时间:2019-04-30 10:04:37

标签: typescript react-native visual-studio-code

我正尝试照常访问我的styles属性,但是,我收到一个错误消息:Cannot read property 'swipeButtonCommon' of undefined

好吧,我的styles对象被定义为无论如何都具有swipeButtonCommon

const styles = StyleSheet.create({
    ...
    swipeButtonCommon:{
        backgroundColor: Color.listActionBackground
    },
   ...
   //swipeButtonLeft and swipeButtonRight are also defined
})

function SwipeButton(title:string, side: 'left' | 'center' | 'right'){
    let styleClass: string | null = null;

    if(side == 'left'){
        styleClass = 'swipeButtonLeft';
    }else if(side == 'right'){
        styleClass = 'swipeButtonRight'
    }
    return (
        <View style={[styles.swipeButtonCommon, styles[styleClass!]]}><Text>{title}</Text></View>
    )
}

我在<View style={...}行中遇到错误,即使我设置了断点,也由于某些原因没有达到目标。我已经清除了Metro Bundler缓存和Haste模块映射,并且尽管没有用,但我已经重新启动了几乎所有内容。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

我发现了问题。我使用的是function ComponentName()语法,这是我通常不习惯的语法。我改用常规的class ComponentName extends Component语法,问题就消失了。