发生这种情况是因为您正在使用
useRef
在功能组件外部,钩子仅在功能组件内部使用。
尝试此代码:
import { StyleSheet, Text, View, FlatList, TouchableOpacity, Dimensions } from 'react-native'
import React, { useState, useRef } from 'react'
const allData = [
{ name: 'Explore', id: '1' },
{ name: 'Trending', id: '2' },
{ name: 'Post', id: '3' },
{ name: 'Messages', id: '4' },
{ name: 'Marketplace', id: '5' }
]
const spacing = 10;
export default function topDynamicBar() {
const reff = useRef()
const [index, setIndex] = useState(2)
return (
<View style={styles.container}>
<FlatList
ref={reff}
initialScrollIndex={index}
keyExtractor={(item) => item.id}
data={allData}
renderItem={({ item, index: findex }) => (<Text style={styles.items}>{item.name}</Text>)}
horizontal
showsHorizontalScrollIndicator={false}
/>
</View>
)
}
const styles = StyleSheet.create({
container:{
backgroundColor:'#000000'
},
items:{
padding:2,
fontSize:30,
height: "auto",
margin:10,
borderColor:'#fff',
borderWidth:2,
borderRadius: spacing
}
})
希望它能解决你的问题