简体   繁体   English

React Native 中的平面列表图像源

[英]Flatlist Image source in React Native

I am trying to render a FlatList in React Native that it will be like an image carousel.我正在尝试在 React Native 中渲染一个FlatList ,它就像一个图像轮播。

I want to provide the image sources in the assets folder and pass each items source in the renderItem but i get error undefined is not an object.我想在 assets 文件夹中提供图像源,并在 renderItem 中传递每个项目源,但我得到错误 undefined is not an object。

Here is the state:这是 state:

export default function App() {
  const [images, setimages] = useState([
    {src:require('./assets/image1.png'),key:'1'},
    {src:require('./assets/image2.png'),key:'2'},
    {src:require('./assets/image3.png'),key:'3'},
    {src:require('./assets/image4.png'),key:'4'},
    {src:require('./assets/image5.png'),key:'5'}
  ]);

And here is the FlatList :这是FlatList

<FlatList
  horizontal={true} 
  showsHorizontalScrollIndicator={false} 
  data={images}
  renderItem={ ({images}) => (
    <Image source={images.src} style={{
      width:260,
      height:300,
      borderWidth:2,
      borderColor:'#d35647',
      resizeMode:'contain',
      margin:8
    }}></Image>
  )}
/>

React Native FlatList renderItem callback get an object parameter with 3 props, item , index and separators : React Native FlatList renderItem回调获取一个带有 3 个道具、 itemindexseparators的对象参数:

renderItem

 renderItem({item, index, separators});

You don't have to define keys in your array, just the images sources and then use item and index inside your renderItem function:您不必在数组中定义键,只需定义图像源,然后在renderItem函数中使用itemindex

Define just an array with the sources:只定义一个带有源的数组:

const [images, setimages] = useState([
  require('./assets/image1.png'),
  require('./assets/image2.png'),
  require('./assets/image3.png'),
  require('./assets/image4.png'),
  require('./assets/image5.png')
]);

And use item and index for source and key :并使用itemindex作为sourcekey

return (
  <FlatList
    horizontal={true} 
    showsHorizontalScrollIndicator={false} 
    data={images}
    renderItem={ ({ item, index }) => (
      <Image source={item} /* Use item to set the image source */
        key={index} /* Important to set a key for list items,
                       but it's wrong to use indexes as keys, see below */
        style={{
          width:260,
          height:300,
          borderWidth:2,
          borderColor:'#d35647',
          resizeMode:'contain',
          margin:8
        }}
      />
    )}
  />
);

UPDATE更新

We should never use indexes for JSX keys because on a rearrangement or the array, we'll end up with the same indexes pointing to different items.我们永远不应该为 JSX 键使用索引,因为在重新排列或数组时,我们最终会得到指向不同项目的相同索引。

There is an ESLint rule regarding that issue eslint-plugin-react :有一个关于该问题的 ESLint 规则eslint-plugin-react

eslint-plugin-react

Prevent usage of Array index in keys (react/no-array-index-key)防止在键中使用数组索引 (react/no-array-index-key)

Warn if an element uses an Array index in its key .如果元素在其key使用 Array 索引,则发出警告。

The key is used by React to identify which items have changed, are added, or are removed and should be stable . React 使用key识别哪些项目已更改、添加或删除,并且应该是 stable

It's a bad idea to use the array index since it doesn't uniquely identify your elements.使用数组索引是一个坏主意,因为它不能唯一标识您的元素。 In cases where the array is sorted or an element is added to the beginning of the array, the index will be changed even though the element representing that index may be the same.在对数组进行排序或将元素添加到数组开头的情况下,即使表示该索引的元素可能相同,索引也会更改。 This results in unnecessary renders.这会导致不必要的渲染。

We should create unique keys for each item ( and maybe store them inside our images array if we have a large items count ) by using some fast hashing algorithms like CRC32 on the image name or by using nanoid to generate a random key for each image.我们应该通过在图像名称上使用一些快速散列算法(如CRC32)或使用nanoid为每个图像生成随机密钥,为每个项目创建唯一的密钥(如果我们有大量项目,可以将它们存储在我们的图像数组中)。

This is happening because you're trying to destructure a images parameter which doesn't exist, it's called item .发生这种情况是因为您试图解构一个不存在的images参数,它被称为item

Try this instead:试试这个:

return (
    <FlatList 
        horizontal
        showsHorizontalScrollIndicator={false}
        data={images}
        renderItem={({ item }) => (
            <Image 
                source={item.src}
                style={{
                    width:260,
                    height:300,
                    borderWidth:2,
                    borderColor:'#d35647',
                    resizeMode:'contain',
                    margin:8
                }}
            />
        )}
    />
);

the comment above is correct, however there is the uri attribute inside the source where you assign the url of the image see:上面的评论是正确的,但是在您分配图像的 url 的源中有uri属性,请参见:

return (
    <FlatList 
        horizontal
        showsHorizontalScrollIndicator={false}
        data={images}
        renderItem={({ item }) => (
            <Image 
                source={{ uri: item.src }}
                style={{
                    width:260,
                    height:300,
                    borderWidth:2,
                    borderColor:'#d35647',
                    resizeMode:'contain',
                    margin:8
                }}
            />
        )}
    />
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM