【问题标题】:add variable to require in ImageBackground在 ImageBackground 中添加要要求的变量
【发布时间】:2021-07-25 07:22:46
【问题描述】:

我正在使用来自 react-native lib 的 ImageBackground。 ImageBackground 使用 source={require('asd.png')} 例如。

但我正在尝试在 require 中添加变量。

const [image,setImage] = useState('./asd.png')

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

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


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

【问题讨论】:

  • 你的图片是network image ??

标签: javascript reactjs react-native imagebackground


【解决方案1】:
// 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 以获得更多帮助。

正如文档所说,

// 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} />;

【讨论】:

  • 但我只需要更改 './asd.png' 名称
  • 为此你应该做的是......创建一个变量const img = require('./something.png').....然后改变它......这样做......setImage(img)
  • 我真的没明白。那我应该在useState中写什么呢?
  • 编辑了答案..再次检查
  • 好吧,伙计,但当我按下并选择新路径时。我只是将路径发送到 setImage('something.png')
猜你喜欢
  • 2011-07-10
  • 2016-09-07
  • 2021-05-27
  • 1970-01-01
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
  • 2016-07-30
相关资源
最近更新 更多