【问题标题】:Images are not showing from state in react native在本机反应中,图像未从状态显示
【发布时间】:2020-01-29 01:22:15
【问题描述】:

我已经在状态中保存了图像名称,但是当我尝试向它们显示时,它给出了错误'Invalid call require('./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>
  )
}

【问题讨论】:

标签: javascript react-native react-native-android


【解决方案1】:

根据documentationIn 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 必须是对象 myImages 中的键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多