【问题标题】:Cannot read property of undefined in React Native style无法读取 React Native 样式中未定义的属性
【发布时间】:2019-09-18 23:25:40
【问题描述】:

我正在尝试像往常一样访问我的 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>
    )
}

我在&lt;View style={...} 行中遇到错误,即使我设置了断点,但由于某种原因它没有命中。我已经清除了 Metro Bundler 缓存和 Haste 模块映射,并且我已经重新启动了几乎所有的东西,尽管没有用。我做错了什么?

【问题讨论】:

  • 你定义swipeButtonLeftswipeButtonRight 的样式了吗???
  • 您是否尝试在SwipeButton func 中打印styles 并查看打印的内容?你也可以在文件中发布完整的代码吗?
  • @HardikVirani 是的,它们已被定义。
  • @yaswanth 它打印undefined
  • @CanPoyrazoğlu 你能把完整的代码贴在文件里吗?

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


【解决方案1】:

我发现了问题。我使用了我通常不习惯的function ComponentName() 语法。我已经切换到常规的class ComponentName extends Component 语法,问题就消失了。

【讨论】:

    猜你喜欢
    • 2021-09-07
    • 2019-09-27
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2018-10-22
    相关资源
    最近更新 更多