admin管理员组

文章数量:1357294

I'm new to react native i'm trying to populate flat list with images. All the images are stored inside the app. I want to set image source dynamically in every iteration. This is what I tried. Please help me.

<FlatList
  data={this.state.listData}
  renderItem={({ item }) => {
   <Image                                                             
    source={
    (item)=>{
     switch(item.TypeX){
     case '1':
     return require('path 1');
     case '2':
     return require('path 2')
   }
}} />
  }
</FlatList>

I'm new to react native i'm trying to populate flat list with images. All the images are stored inside the app. I want to set image source dynamically in every iteration. This is what I tried. Please help me.

<FlatList
  data={this.state.listData}
  renderItem={({ item }) => {
   <Image                                                             
    source={
    (item)=>{
     switch(item.TypeX){
     case '1':
     return require('path 1');
     case '2':
     return require('path 2')
   }
}} />
  }
</FlatList>
Share Improve this question asked Nov 30, 2018 at 8:06 plwplw 211 silver badge5 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

You should have images in the data .. in your case in listDate

state = {
  listData: [
  {...,image:require('1.png')},
  {...,image:require('2.png')}
  ...
 ]
}

Then in your render function

<FlatList
  data={this.state.listData}
  renderItem={({ item }) => {
   <Image                                                             
    source={item.image}
}} />
  }
</FlatList>

If you have the images stored in remote url then your state should look like

state = {
      listData: [
      {...,image: 'https://somedomain./imagename.png'},
      {...,image: 'https://somedomain./imagename2.png'}
      ...
     ]
    }

and in your render function you should use following code

<FlatList
  data={this.state.listData}
  renderItem={({ item }) => {
   <Image                                                             
    source={{uri: item.image}}
}} />
  }
</FlatList>

If you are fetching record from the api you place the request in ponentDidMount react callback and set the data using setState function

I think putting switch inside image source prop is not a good idea. Also not sure whether it will work or not. But, you can do one thing..when you are getting data from API that you are filling in your listData array you can append your images' url/path just after getting data from API for eg you receive an array of objects in response:

res=[ { data1:'', data2:''..   },{ data1:'', data2:''.. },{ data1:'', data2:''.. },{ 
   data1:'', data2:''.. }];

so you can iterate the this array and append the images like this:

res.map((obj, i) => { 
   let path = imagepPathArray[i]; 
   return {...obj, imagePath: path  
   }
})

and access image path like this in FlatList:

renderItem={({ item }) => {
   <Image                                                             
    source={{uri: item.imagePath}}
}}

PS: store image paths in separate array first.

I found a soliution , we can create simple function like below in our ponet

getFanSpeedImage(speed) {
        switch (speed) {
            case '1':
                return (<Image style={styles.statusButton} source={require('1.png')} />);
            case '2':
                return (<Image style={styles.statusButton} source={require('2.png')} />);
            case '3':
                return (<Image style={styles.statusButton} source={require('3.png')} />);
        }

    }

after that we can call it in out main render function like below

render(){
   return(

<FlatList
  data={this.state.listData}
  renderItem={({ item }) => {
    {this.getFanSpeedImage(item.typeX)}
  }
</FlatList>

);

}

Whenever you have to display images while using Flatlist its good practice if you keep them in an array which you pass as a data to the Flatlist

Hence, first of all, try to structure your data as follows.

const data = [{
    id: 1,
    name: 'Pikachu',
    image: require('./path/pikachu.png'),
  },
  {
    id: 2,
    name: 'One Plus',
    image: require('./path/onPlus.png'),
  },
  {
    id: 3,
    name: 'Hero Go Pro',
    image: require('./path/goPro.png'),
  },
]

Note the require keyword in the data this will automatically import the required images and now we pass this data to the Flatlist as follows

<FlatList
  showsVerticalScrollIndicator={false}
  data={data}
  renderItem={({item}) => <MyComponent data={item} />} 
  keyExtractor={item => item.id}
  numColumns={2}
  />

Now that we have passed the data to <MyComponent/> it will be accessible in the same ponent and we can do the following to use it to display the image

<Image source={this.props.data.image} style={{height:20, width:20}}/>

Hope this helps

You can also use https://www.npmjs./package/react-native-placeholderimage library.This library helps to put placeholder until your image is not downloaded from internet or API.

renderItem={({item}) =>
    <PlaceHolderImage
    source={!!data.imageurl ? { uri: imgURL } : AppImages.placeHolderImage.source}
    style={iconStyle}
    placeHolderURI={AppImages.placeholderImage.source}
                    />
}

本文标签: javascriptHow to dynamically set reactnative image source inside flat listStack Overflow