首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ImageBackground中添加需要的变量

在ImageBackground中添加需要的变量
EN

Stack Overflow用户
提问于 2021-05-03 01:50:38
回答 1查看 39关注 0票数 1

我使用的是来自react-native库的ImageBackground。例如,使用source={ ImageBackground (‘asd.png’)}请求。

但我正在尝试将变量添加到require.

代码语言:javascript
复制
const [image,setImage] = useState('./asd.png')

.then(image => {
            setImage(image.path) // gives 'something.png'
          });

<ImageBackground source={require(image)></ImageBackground> 

但是我得到了错误。第122行的无效调用: require(image)

EN

回答 1

Stack Overflow用户

发布于 2021-05-03 02:01:43

代码语言:javascript
复制
// Declare a varible here...
const img = require('./asd.png')  

// Example of a network image
const networkImage = "https://images.pexels.com/photos/799443/pexels-photo-799443.jpeg"  

const [image, setImage] = useState(img) // Use it here like this

// Static Image Usage
<ImageBackground 
    source={image} 
    style={{ flex: 1, resizeMode: 'cover', justifyContent: 'center' }}>
</ImageBackground> 

// Network Image Usage
<ImageBackground 
    source={{uri : networkImage}} 
    style={{ flex: 1, resizeMode: 'cover', justifyContent: 'center' }}>
</ImageBackground> 

这是使用ImageBackground的正确方式

检查此Snack以查看工作示例

此外,请查看docs以获得更多帮助。

就像医生说的那样

代码语言:javascript
复制
// GOOD (this is also correct)
<Image source={require('./my-icon.png')} />;

// BAD (this is wrong...)
var icon = this.props.active
  ? 'my-icon-active'
  : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />;

// GOOD (this is correct)
var icon = this.props.active
  ? require('./my-icon-active.png')
  : require('./my-icon-inactive.png');
<Image source={icon} />;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67359482

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档