You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法创建含ScrollView子组件的Accordion,滚动功能失效求助

实现带ScrollView的React Native Reanimated折叠面板

以下是可直接运行的实现方案,解决了折叠面板嵌套滚动视图的布局和手势冲突问题:

完整代码示例

import React, { useState } from 'react';
import { View, ScrollView, Text, StyleSheet } from 'react-native';
import { Accordion } from 'react-native-reanimated';

// 模拟面板数据
const panelList = [
  {
    title: '基础设置',
    options: ['账号绑定', '通知权限', '隐私设置', '语言切换', '主题模式']
  },
  {
    title: '功能选项',
    options: ['离线缓存', '数据同步', '快捷操作', '自定义快捷键']
  },
  {
    title: '帮助与反馈',
    options: ['使用指南', '常见问题', '意见反馈', '联系客服']
  }
];

const AccordionWithScroll = () => {
  // 跟踪展开的面板索引
  const [expandedPanels, setExpandedPanels] = useState([]);

  const togglePanel = (index) => {
    setExpandedPanels(prev => 
      prev.includes(index) ? prev.filter(i => i !== index) : [...prev, index]
    );
  };

  return (
    <View style={styles.container}>
      {panelList.map((panel, index) => (
        <Accordion
          key={index}
          title={() => (
            <View style={styles.panelTitle}>
              <Text style={styles.titleText}>{panel.title}</Text>
            </View>
          )}
          content={() => (
            <ScrollView
              style={styles.scrollContent}
              // 折叠时禁用滚动手势,避免冲突
              pointerEvents={expandedPanels.includes(index) ? 'auto' : 'none'}
            >
              {panel.options.map((opt, optIndex) => (
                <View key={optIndex} style={styles.optionItem}>
                  <Text style={styles.optionText}>{opt}</Text>
                </View>
              ))}
            </ScrollView>
          )}
          onToggle={() => togglePanel(index)}
          style={styles.accordionPanel}
        />
      ))}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
    backgroundColor: '#f8f9fa'
  },
  accordionPanel: {
    marginBottom: 12,
    backgroundColor: '#fff',
    borderRadius: 8,
    overflow: 'hidden', // 防止折叠时内容溢出
  },
  panelTitle: {
    paddingVertical: 16,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#e9ecef'
  },
  titleText: {
    fontSize: 16,
    fontWeight: '500',
    color: '#343a40'
  },
  scrollContent: {
    flexGrow: 1, // 关键:让ScrollView自动填充面板展开后的可用空间
    padding: 16
  },
  optionItem: {
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f1f3f5'
  },
  optionText: {
    fontSize: 14,
    color: '#495057'
  }
});

export default AccordionWithScroll;

关键注意事项

  • flexGrow: 1:给ScrollView设置该样式,确保它能在面板展开时自动适配高度,避免滚动视图高度塌陷。
  • overflow: hidden:给Accordion组件添加该样式,防止折叠时ScrollView的内容溢出面板边界。
  • 手势冲突处理:通过pointerEvents控制ScrollView的手势可用性,折叠时禁用滚动,避免点击面板标题时误触发滚动。

内容的提问来源于stack exchange,提问作者GabVlado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 05:26:05