簡體   English   中英

反應本機輪播 UseState

[英]React Native Carousel UseState

我目前正在實施一個輪播庫 ( react-native-reanimated-carousel )。 以下代碼表示如下:

<Carousel
      width={cardWidth}
      height={cardHeight}
      data={cards}
      onScrollEnd={() => {console.log('ended')}}
      renderItem={({item}) => 
      (
        <View>
          <Image 
          source={{uri: item["ImgURL"],}}
          style={styles.card}
          />
        </View>
      )}
    />

旋轉木馬發生變化時, renderItem屬性中的item值也會發生變化。 有沒有辦法從該元素外部獲取item的值? 我希望外部的其他元素根據item的值(和屬性)進行更改。

您可以嘗試在renderItem function 中調用回調 function。

() => {
  const [activeItem, setActiveItem] = useState(cards[0].item);

  return (<Carousel
    width={cardWidth}
    height={cardHeight}
    data={cards}
    onScrollEnd={() => {console.log('ended')}}
    renderItem={({item}) => {

      setActiveItem(item);

      return (
        <View>
          <Image 
          source={{uri: item["ImgURL"],}}
          style={styles.card}
          />
        </View>
      );
    }}
    />)
  );
};

或者你可以使用 onScrollEnd。 它根據文檔提供了以前的索引和當前索引

() => {
  const [activeItem, setActiveItem] = useState(cards[0].item);

  return (<Carousel
    width={cardWidth}
    height={cardHeight}
    data={cards}
    onScrollEnd={(previous, current) => {
      setActiveItem(cards[current].item);
      console.log('ended')
    }}
    renderItem={({item}) => (
        <View>
          <Image 
          source={{uri: item["ImgURL"],}}
          style={styles.card}
          />
        </View>
    )}
    />)
  );
};

或者你可以使用 Ref 道具getCurrentIndex

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM