如何在React Native中动态显示图像?

时间:2020-09-28 17:27:14

标签: reactjs react-native

我现在使用静态显示的彩色框作为视觉参考,但是需要将它们替换为阵列中的图像。如何使用数组动态显示这些图像?图像也会不时更改。代码如下所示,以及现在的样子:

 <View style={{ flex: 0.8, alignItems: 'center' }}>
    <View style={{ flexDirection: 'row', justifyContent: 'center', marginTop: 10 }}>
       <View style={{ width: 180, height: 310, backgroundColor: 'red', marginRight: 10 }} />

           <View style={{ flexDirection: 'column' }}>
              <View style={{ width: 180, height: 150, backgroundColor: 'blue', marginBottom: 10 }} />
              <View style={{ width: 180, height: 150, backgroundColor: 'green' }} />
           </View>
     </View>
     <View style={{ width: 370, height: 150, backgroundColor: 'purple', marginTop: 10 }} />

           <View style={{ flexDirection: 'row', justifyContent: 'center', marginTop: 10 }}>
               <View style={{ marginRight: 10, width: 180, height: 150, backgroundColor: 'blue' }} />
               <View style={{ width: 180, height: 150, backgroundColor: 'green' }} />
           </View>

           <View style={{ flexDirection: 'row', justifyContent: 'center', marginTop: 10 }}>
              <View style={{ marginRight: 10, width: 180, height: 180, backgroundColor: 'green' }} />
              <View style={{ width: 180, height: 180, backgroundColor: 'blue' }} />
           </View>
      <View style={{ marginTop: 10, width: 370, height: 150, backgroundColor: 'purple' }} />
 </View>

enter image description here

1 个答案:

答案 0 :(得分:0)

此布局是否固定?

(此解决方案并不美观) 您可以在状态下创建一个包含图片网址的数组: this.state = {imgDict:{0:'... url',1:'... url'}}

然后,对于每个矩形,您将拥有

<View style={ styles.view_style }>
  this._displayImage(imgIndex)
</View>

您将拥有以下功能:

_displayImage(imgIndex) {
  if (imgIndex in this.state.imgDict) { 
    return (<Image source={{ uri: this.state.imgDict[imgIndex] }} style={ styles.imgStyle }/>)
  }
}

注意:如果要更改state.imgDict,为了让RN了解字典已更改,请不能执行以下操作:

this.state.imgDict[imgIndex] = "new_url"

您必须这样做:

var newImgDict = {...this.state.imgDict}
newImgDict[imgIndex] = "new_url"
this.setState({ imgDict: newImgDict })

(/不是很好的解决方案,但这应该可以为您提供见解)