Реализовать функцию перетаскивания в дочерних элементах массива в React Native - PullRequest
0 голосов
/ 04 мая 2020

Я успешно реализовал (с некоторой помощью этого сообщества) свертываемый список с заголовками, использующими accordian / collapsible. Я хотел бы реализовать функцию перетаскивания для элементов списка, чтобы пользователь мог изменить их порядок по мере необходимости. Я пробовал реагировать-родной-draggable-flatlist, но был успешным только с данными уровня заголовка. Не с детскими вещами. Любая помощь приветствуется. Пожалуйста, найдите мой код ниже.

Главный экран

Приложение. js

import React, { useState } from "react";
import {StyleSheet,View,SectionList, Text,TouchableOpacity,Animated,Easing} from "react-native";
import Constants from "expo-constants";
import Accordion from 'react-native-collapsible/Accordion';

import Header from './components/header.js';
import Item from './components/item.js';

const styles = StyleSheet.create({

  container: {
    flex: 1,
    backgroundColor: 'black',
    marginTop: Constants.statusBarHeight,
  },
  header: {
    fontSize: 20,
    color: 'teal',
    alignSelf: 'center',
    marginTop: 20,
    marginBottom: 7,
  }
});

function App(){

  const [listData, setListData] = useState([
    {
      id: 1,
      isCollapsed: true,
      title: "Work",
      data: [
        {
          text: 'MSD',
          key: 1
        },
        {
          text: 'Cosmo',
          key: 2
        },
        {
          text: 'Jackson',
          key: 3
        },
      ]
    },
    {
      id: 2,
      title: "Home",
      isCollapsed: true,
      data: [
        {
          text: 'Gym',
          key: 4
        },
        {
          text: 'Dinner',
          key: 5
        },
        {
          text: 'React',
          key: 6
        },
      ]
    },
  ]);  

  const [activeSections,setActiveSections] = useState([])

  const renderHeader = section => {
    return (
      <View>
        <Text style={styles.header}>{section.title}</Text>
      </View>
    );
  };

  const renderContent = section => {
    return (
      section.data.map((item) => <Item key={item.key} data={item.text} dataID={item.key} onDeleteHandler={onDeleteHandler}/>)
    )
  };

  const updateSections = activeSections => {
    setActiveSections(activeSections);
  };


  const onDeleteHandler = (key) => {

      setListData(listData => listData.map(category => ({
          ...category,
         data: category.data.filter(item => item.key !== key)
       })
     ));
  }

  return(

    <View style={styles.container}>
      <Header />      
      {/* 2. List with Accordian */}
      <Accordion
        sections={listData}
        activeSections={activeSections}
        renderHeader={renderHeader}
        renderContent={renderContent}
        onChange={updateSections}
        expandMultiple={true}
      />
    </View>
  )
};


export default App;

Компонент поз. js

import React from "react";
import {Text, StyleSheet,View, TouchableOpacity} from "react-native";
import { Entypo } from '@expo/vector-icons';

const styles = StyleSheet.create({

    itemGroup: {
      flexDirection: 'row',
      justifyContent: 'center'
    },

    checkBoxAndDeleteStyle: {
      marginTop: 9,
    },

    item: {
      flex: 1,
      padding: 10,
      marginLeft: 5,
      marginBottom: 5,
      marginRight: 5,
      borderWidth: 0.8,
      borderStyle: 'dashed',
      borderRadius: 10,
      borderColor: '#00adce',
    },

    toDoText: {
      fontSize: 12,
      color: 'white'
    },

    toDoTextStrikeThrough: {
      fontSize: 12,
      color: 'grey',
      textDecorationLine: 'line-through'
    },

    animatedView: {
      width: 100,
      height: 100,
      backgroundColor: 'orange',
      margin: 5
    }
  });



const Item = ({ data, dataID, onDeleteHandler }) => {

    const [checked, setChecked] = React.useState(false);

    const toggleChecked = () => {
      if (checked == true){ 
        setChecked(false)
      }
      else{
        setChecked(true)
      }
    }


    return(
      <View style={styles.itemGroup}>
        <TouchableOpacity style={styles.item} onPress={toggleChecked}>
          <View>
            <Text style={checked === true ? styles.toDoTextStrikeThrough : styles.toDoText}>{data}</Text>
          </View>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => onDeleteHandler(dataID)}>
          <View style={styles.checkBoxAndDeleteStyle}>
            <Entypo name="cross" color='#004d4d' size={18}/>
          </View>
        </TouchableOpacity>
      </View>
    )
  };

export default Item;
...