首页 > 解决方案 > 在本机反应中,图像未从状态显示

问题描述

我已经在状态中保存了图像名称,但是当我尝试显示它们时,它给出了错误“无效调用需要('./assets/'+this.state.img1)”(但是当我将图像名称直接放在源中时它的开头工作。喜欢:我也提醒该州它具有相同的图像名称。

  render() {
  return (
  <TouchableOpacity onPress={this.onItemPressed} style={styles.container}>

       <Image
        style={styles.stretch}
        source={require('./assets/'+this.state.img1)}
      />
       <Image
        style={styles.stretch}
        source={require('./assets/'+this.state.img2)}
      />
    </TouchableOpacity>
  )
}

标签: javascriptreact-nativereact-native-android

解决方案


根据文档In order for this to work, the image name in require has to be known statically.

// GOOD
<Image source={require('./my-icon.png')} />;

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

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

您可以做的是构建映射/对象:

const myImages = {
  img1: require('/path/to/img1'),
  img2: require('/path/to/img2'),
};

render() {
  return (
  <TouchableOpacity onPress={this.onItemPressed} style={styles.container}>

       <Image
        style={styles.stretch}
        source={myImages[this.state.img1]}
      />
       <Image
        style={styles.stretch}
        source={myImages[this.state.img2]}
      />
    </TouchableOpacity>
  )
}

为此,this.state.img1this.state.img2必须是 object 中的一个键myImages


推荐阅读