如何固定ScrollView内右下角图标,不随内容滚动且不遮挡内容?
解决方案
你可以通过「外层容器嵌套+图标绝对定位+ScrollView底部预留边距」的方式实现需求,完美解决图标固定和内容不被截断的问题,具体实现逻辑如下:
- 在ScrollView外层包裹一个占满可用高度的父容器,设置定位属性为相对定位
- 将
<AddnewAlerts />组件从ScrollView内部移出,放在和ScrollView同级的位置 - 给
<AddnewAlerts />的外层容器设置绝对定位,固定在右下角 - 给ScrollView的
contentContainerStyle添加底部内边距,数值至少为图标高度+你需要的底部边距,保证滚动到底部时内容不会被图标遮挡
修改后的代码示例:
<View style={{flex: 1, position: 'relative'}}> <ScrollView contentContainerStyle={{ paddingBottom: 80, // 可根据你的图标尺寸调整,比如图标高50、底部留30边距就设80 flexGrow: 1 }} > {this.state.alertData && this.state.alertData.map((item, index) => { return ( <View> <TouchableOpacity style={styles.alertContainer} onPress={() => this.onCardClick(index, true)} > <View style={{ flexDirection: "row", justifyContent: "space-between", }} > <Text style={styles.title}>{item.title}</Text> <View style={{ flexDirection: "row", }} > <Text style={styles.sideText}>Il y a 2h</Text> {item.status && ( <Away style={{ marginLeft: 5, marginTop: 6 }} /> )} </View> </View> <View style={{ marginBottom: 10 }}> <Text style={styles.primaryText}>{item.primaryText}</Text> <Text style={styles.secondaryText}> {item.secondaryText} </Text> </View> <View> <Text style={styles.primaryText}>Message</Text> <Text style={styles.secondaryText}>{item.message}</Text> </View> {this.state.selectedCard[index] && ( <Image style={{ height: 250, width: 300 }} source={item.image} /> )} </TouchableOpacity> <Close style={{ top: 10, right: -5, position: "absolute" }} onPress={() => this.toggleModal(index)} /> </View> ); })} </ScrollView> {/* 固定在右下角的图标 */} <View style={{ position: 'absolute', bottom: 20, right: 20, zIndex: 999, elevation: 10 // 安卓端需要加这个属性保证图标不被遮挡 }}> <AddnewAlerts /> </View> </View>
原理解释:ScrollView内部的所有元素都属于滚动内容容器的子节点,即使设置绝对定位也是相对于滚动内容容器,滚动时内容容器整体位移,图标自然会跟着滚动。将图标移到外层固定的父容器下,绝对定位会相对于不动的父容器生效,同时ScrollView底部预留的内边距可以保证滚动到底部时所有内容都能正常展示,不会被图标遮挡。
内容的提问来源于stack exchange,提问作者Shreya B
相关产品推荐
相关产品推荐

