首页 > 解决方案 > TypeError:未定义不是对象(评估'style.width')

问题描述

          <TouchableOpacity style={styles.box}>
            <ImageBackground
              source={require('../images/pic.png')}
            >
                <Icon
                  type='foundation'
                  name='dump'
                  style={styles.icon}
                />
            </ImageBackground>

            <Text style={styles.text}>
            Hello
            </Text>
          </TouchableOpacity>

嗨,我在使用 imagebackground 时不断收到 TypeError: undefined is not an object (evaluate 'style.width') 错误。为什么会出现这种情况?

标签: react-native

解决方案


这是来自 imageBackground 的 RN 文档,它说您应该为图像背景添加高度和宽度以使其正常工作。

请注意,您必须指定一些宽度和高度样式属性。

因此,只需将您的代码替换为以下内容:

 <TouchableOpacity style={styles.box}>
                <ImageBackground
                  source={require('../images/pic.png')}
                  style={{width: '100%', height: '100%'}} // new addition
                >
                    <Icon
                      type='foundation'
                      name='dump'
                      style={styles.icon}
                    />
                </ImageBackground>

                <Text style={styles.text}>
                Hello
                </Text>
              </TouchableOpacity>

推荐阅读