问题描述
我遵循了本教程,以便使用带有图像的滑块:https://www.youtube.com/watch?v=HAgJqaJc-ck
Carousel.js
const Carousel = ({data}) => {
const scrollX = new Animated.Value(0)
let position = Animated.divide(scrollX,width)
if (data && data.length){
return (
<View>
<FlatList data = {data}
keyExtractor= {(item,index) => 'key' + index}
horizontal
pagingEnabled
scrollEnabled
snapToAlignment = 'center'
scrollEventThrottle = {16}
decelerationRate = {"fast"}
showsHorizontalScrollIndicator = {false}
renderItem = {({item}) => {
return <CarouselItem item= {item} navigation={props.navigation}/>
}}
onScroll = {Animated.event(
[{nativeEvent : {contentOffset: { x : scrollX}}}]
)}
/>
<View style = {styles.dotView}>
{data.map((_,i) => {
let opacity = position.interpolate({
inputRange : [i - 1,i,i + 1],outputRange: [0.3,1,0.3],extrapolate : 'clamp'
})
return <Animated.View
key={i}
style = {{opacity,height : 10,width : 10,background: '#595959',margin: 8,borderRadius: 5}}
/>
})}
</View>
</View>
)
}
console.log('Please provide Images')
return null
}
CarouselItem.js
const CarouselItem = ({item,navigation}) => {
const url = item.url
return (
<View style={styles.cardView} >
<TouchableOpacity onPress={() => props.navigation.navigate("BoatInfo")}><Image style={styles.image} source={{uri: item.url}} /></TouchableOpacity>
<View style={styles.textView}>
<Text style={styles.itemTitle}>{item.title}</Text>
<Text style={styles.imageDescription}>{item.description}</Text>
</View>
</View>
)
}
还有Data.js
export const dummyData = [
{
title: 'BOAT DETAILS',url : require('../component/schema.jpg'),description: 'PDF containing the specificities of the boat',id : 1
},{
title: 'TUTORIALS',url : require('../component/tuto.png'),description: 'Become a capitain by watching these videos',id : 2
},{
title: 'YOUR TRIP',url : require('../component/trip.png'),description: 'Follow your trip details',id : 3
},]
现在,正如您在CarouselItem中看到的那样,我正在尝试添加一项功能,以便当我按图像时,它将带我到另一页(每张图片将我带到另一页)。但是,当我尝试这样做时,出现以下错误:
所以,我了解道具中的内容是空的...
但是当我将const CarouselItem = ({ item },props) => {
切换为const CarouselItem = ( props,{ item }) => {
时,出现以下错误:
我不明白的是,当我删除{item}时,导航起作用;而当我删除道具时,{item}起作用...两者如何工作?我在做什么错了?
解决方法
您还必须从平面列表中传递带有项目对象的导航道具对象
导航= {props.navigation} item = {item} 在关键功能中,您必须这样写 crousalItem =(项目,导航)=> 这样,您就可以同时获得项目和导航对象。 使用项目列出数据,navigation.navigate()移至另一个屏幕
, React Native中的 Only screens自动访问导航道具,因此您需要将其传递给CarouselItem组件,然后使用总是很有趣的object destructuring来在组件中获取特定的道具(就像您对item
所做的那样)。它应该看起来像这样:
...
renderItem = {({item}) => {
return <CarouselItem item={item} navigation={navigation}/>
}}
...
然后:
const CarouselItem = ({ item,navigation }) => {
...
那应该可行!
祝你好运!