更改方向时如何更改Flatlist的numColumns

问题描述

我创建了函数名称getOrientation()并将其放在useEffect上,以便每当旋转设备时,它将重新渲染组件并向我显示设备的方向。

我还创建了变量以使用钩子确定方向

getOrientation()

const [orientation,setOrientation] = useState("")

const window = useWindowDimensions()
const getOrientation = () => {
    if (window.height < window.width) {
        setOrientation("LANDSCAPE")
    } else {
        setOrientation("PORTRAIT")
    }
    return orientation
}

使用时效果

useEffect(() => {
    getOrientation()
})
console.log(orientation)

我的问题是我想在Flatlist(LANDSCAPE)中将numsColumns设置为2,在纵向模式下等于1,但是错误弹出窗口告诉我不能即时更改numColumns。我该怎么办?

这是我的单位列表

<View style={styles.container}>
        <FlatList
            contentContainerStyle={{
                paddingLeft: insets.left,paddingRight: insets.right,}}
            data={dishes.dishes}
            numColumns={orientation == "LANDSCAPE" ? 2 : 1}
            renderItem={({ item,index }) => (
             
                <Tile
                    style={styles.tileItem}
                    key={index}
                    title={item.name}
                    caption={item.description}
                    onPress={() => navigation.navigate('Dishdetail_Screen',{ dishId: item.id })} // passing infor from one to another screen
                    // chevron={false}
                    featured
                    imageSrc={{
                        uri: baseUrl + item.image
                    }}
                />
             

            )}
            keyExtractor={item => item.id.toString()} />
    </View>

此令人毛骨悚然的错误 enter image description here

P / s:我是新的React-Native开发人员。感谢所有检查我的问题的人

解决方法

尝试像这样向您的Flatlist添加关键道具,其值就是您的方向:

 <FlatList
            key={orientation} // add key prop here
            contentContainerStyle={{
                paddingLeft: insets.left,paddingRight: insets.right,}}
            data={dishes.dishes}
            numColumns={orientation == "LANDSCAPE" ? 2 : 1}
            renderItem={({ item,index }) => (
             
                <Tile
                    style={styles.tileItem}
                    key={index}
                    title={item.name}
                    caption={item.description}
                    onPress={() => navigation.navigate('Dishdetail_Screen',{ dishId: item.id })} // passing infor from one to another screen
                    // chevron={false}
                    featured
                    imageSrc={{
                        uri: baseUrl + item.image
                    }}
                />
             

            )}
            keyExtractor={item => item.id.toString()} />

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...