我无法创建带有 Scrollview 子项的手风琴,这不会滚动

问题描述 投票:0回答:1

有人可以帮助我吗,我想制作一个手风琴,并且在每个选项中它将包含一个带有多个选项的 ScrollView。我尝试按照文档中的示例进行操作,但没有成功。

文档,https://docs.swmansion.com/react-native-reanimated/examples/accordion/

reactjs react-native expo react-native-reanimated
1个回答
0
投票
import React, { useState } from 'react';
import { View, Text, ScrollView, TouchableOpacity, StyleSheet } from 'react-native';
import Animated, { useAnimatedStyle, withSpring } from 'react-native-reanimated';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import 'react-native-gesture-handler';

const AccordionItem = ({ title, content }) => {
  const [expanded, setExpanded] = useState(false);

  const animatedHeight = useAnimatedStyle(() => {
    return {
      height: withSpring(expanded ? 200 : 0, { damping: 15, stiffness: 90 }),
    };
  });

  return (
    <View style={styles.itemContainer}>
      <TouchableOpacity onPress={() => setExpanded(!expanded)} style={styles.header}>
        <Text style={styles.headerText}>{title}</Text>
      </TouchableOpacity>
      <Animated.View style={[styles.contentContainer, animatedHeight]}>
        <ScrollView style={styles.scrollView}>
          {content.map((item, index) => (
            <Text key={index} style={styles.contentText}>
              {item}
            </Text>
          ))}
        </ScrollView>
      </Animated.View>
    </View>
  );
};

const Accordion = () => {
  const data = [
    {
      title: 'Section 1',
      content: ['Option 1.1', 'Option 1.2', 'Option 1.3', 'Option 1.4', 'Option 1.5', 'Option 1.2', 'Option 1.3', 'Option 1.4', 'Option 1.5', 'Option 1.2', 'Option 1.3', 'Option 1.4', 'Option 1.5']
    },
    {
      title: 'Section 2',
      content: ['Option 2.1', 'Option 2.2', 'Option 2.3', 'Option 2.4', 'Option 2.5'],
    },
    {
      title: 'Section 3',
      content: ['Option 3.1', 'Option 3.2', 'Option 3.3', 'Option 3.4', 'Option 3.5'],
    },
  ];

  return (
    <View style={styles.container}>
      {data.map((item, index) => (
        <AccordionItem key={index} title={item.title} content={item.content} />
      ))}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 10,
    paddingTop: 90,
  },
  itemContainer: {
    marginBottom: 10,
    borderRadius: 5,
    overflow: 'hidden',
    backgroundColor: '#fff',
    elevation: 2,
  },
  header: {
    padding: 15,
    backgroundColor: '#6200ee',
  },
  headerText: {
    color: '#fff',
    fontWeight: 'bold',
  },
  contentContainer: {
    overflow: 'hidden',
  },
  scrollView: {
    padding: 15,
    backgroundColor: '#f1f1f1',
  },
  contentText: {
    marginBottom: 10,
  },
});

export default function App() {
  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <Accordion />
    </GestureHandlerRootView>
  );
}

希望这对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.