首页 > 解决方案 > 如何使用状态制作动态图像 - 反应原生

问题描述

我的功能是:

  getImage(page){
    return
    (
      <Image
      style={{position:'absolute',height:'60%',width:'90%',padding:50,bottom:30 ,alignSelf: 'center' }}
      source={require('../../images/backgrounds/introduction/'+page.img)}
        />
    )
  }

render(){
return (
...
{this.getImage(activePage)}
)
}

但我收到此错误消息:

Error: /Users/***/components/login/Introduction.js:85:14: calls to `require` expect exactly 1 string literal argument, but this was found: `require('../../images/backgrounds/introduction/' + page.img)`.

标签: javascriptreact-native

解决方案


require()你可以使用而不是串联state

初始化一个状态说imageArray={page1:require('link of page 1 image'),page2:require('link of page 2 image')}

然后像这样getImage()使用,Image

<Image
  style={{position:'absolute',height:'60%',width:'90%',padding:50,bottom:30 ,alignSelf: 'center' }}
  source={this.state.imageArray[page]}
    />

其中page是状态项之一的密钥imageArray


推荐阅读