简体   繁体   中英

How to Implement Swipable list in react native?

I've implemented an app based on react native. This app shows me a list via swipelistview. But I have a Problem. when list add new items after scroll down, swipelistview won't work properly. In fact it works by Accident. I don't know where i've made mistake. this is my code:


import React , {Component} from 'react';
import { StyleSheet, Text, View, FlatList ,ActivityIndicator,Animated , TouchableOpacity, Alert } from 'react-native';
import { SwipeListView } from 'react-native-swipe-list-view';
import { Container, Header, Content, Accordion ,Icon ,Item, Input , Button ,ActionSheet ,  Card, CardItem, Body} from "native-base";

var DESTRUCTIVE_INDEX = 3;
var CANCEL_INDEX = 4;
class App extends Component {
  constructor(props) {
      super(props);
       this.actionSheet = null;

    }

  state = {
      data: [],
      filteredData: [],
      page: 1,
      loading: false,
      error: null,
      spinner: false,
      searchText:'',
      lety:false,
      refreshing: false
    };


  componentDidMount() {
      console.disableYellowBox = true;
      this.fetchData();
  }

  handleLoadMore = () => {
    this.setState(
      {
        page: this.state.page + 1
      },
      () => {
        this.fetchData();
      }
    );
  };
  fetchData = () => {
    const page  = this.state.page;
    this.setState({ loading: true });

    let response = fetch(
     'http://webgispro.ir/home/GetWords/' + page ,
     {
       method: "POST"

     }
    ).then((response) => response.json())
     .then((responseJson) => {

       this.setState(
         {
            data : page === 1 ? Array.from(responseJson): [...this.state.data, ...responseJson] ,
            loading: false,
            refreshing: false
         })
     })
     .catch((error) => {
          this.setState({ error, loading: false });
     });

  };

  searchData = (searchText) => {
    this.setState({searchText: searchText.toLowerCase()});
    if (searchText =='') {
       this.setState({filteredData: []});
       this.setState({lety:false})
       return false;
    }

    let filteredData = this.state.data.filter(function (item) {
        return item.Word.toLowerCase().includes(searchText.toLowerCase());
    });
    this.setState({lety : filteredData.length == 0 ? true : false})
    this.setState({filteredData: filteredData});
  };
  renderHeader = () => {
    return <Searchbar
      style={{ width:'100%' }}
      inputStyle={{borderWidth: 0}}
      round={false}
      lightTheme={true}
      placeholder="Search..."
      autoCapitalize='none'
      autoCorrect={false}
      onChangeText={this.searchData}
      value={this.state.searchText}
    />
  };
  renderFooter = () => {
    if (!this.state.loading) return null;

    return (
      <View
        style={{
          paddingVertical: 20,
          borderTopWidth: 1,
          borderColor: "#CED0CE"
        }}
      >
        <ActivityIndicator animating ={true} color="blue" style={{height: 80, marginTop: 10, opacity: 1 }} size="large" />
      </View>
    );
  };
  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "100%",
          backgroundColor: "#CED0CE",
          //marginLeft: "14%"
        }}
      />
    );
  };
  handleRefresh = () => {
    this.rowHeightAnimatedValues = {};
    this.setState(
      {
        page: 1,
        refreshing: true
      },
      () => {
        this.fetchData();
      }
    );
  };

  editItem = key => () => {
    var example = this.state.data.find(o=>o.Id == key).Example

    if ( this.actionSheet !== null ) {
            const title = <Text style={{ color: 'black', fontSize: 23 }}>{example}</Text>
            this.actionSheet._root.showActionSheet(
              {
                options: [] ,
                cancelButtonIndex: CANCEL_INDEX,
                destructiveButtonIndex: DESTRUCTIVE_INDEX,
                title:title
              }, (i) => console.log(i));
        }
  }

  deleteItem = key => () => {
    Alert.alert(
    "???",
    "??? ???? ??? ????? ????? ??",
    [
      {
        text: "???",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel"
      },
      { text: "???", onPress: () => console.log("OK Pressed") }
    ],
    { cancelable: false }
  );
  }

  onRowOpen =() => {

     console.log('cfdfdf')

  }
  render() {
    return (
      <View style={styles.container}>
      <Header searchBar rounded>
          <Item>
            <Icon name="ios-search" />
            <Input placeholder="Search" onChangeText={this.searchData} />
            <Icon name="ios-people" />
          </Item>
          <Button transparent>
            <Text>Search</Text>
          </Button>
        </Header>
        <SwipeListView
          useFlatList
          extraData={this.state}
          data={this.state.filteredData && this.state.filteredData.length > 0 || this.state.lety == true ? this.state.filteredData : this.state.data}
          keyExtractor={item => item.Id.toString()}
          renderItem={(data, rowMap) => (
            <Animated.View
              style={[
                styles.rowFront,
                data.index % 2 === 0 && { backgroundColor: 'white' },
                { height: 100 }
              ]}
            >
              <Text style={{position: 'absolute', top: 35 , fontSize:20}}>
                 {data.item.Word}
              </Text>

            </Animated.View>
          )}
          renderHiddenItem={ (data, rowMap) => (
            <View style={styles.rowBack}>
              <Text style={{fontSize:20}}>{data.item.Meaning}</Text>
              <TouchableOpacity style={[styles.backRightBtn, styles.backRightBtnLeft]} onPress={this.editItem(data.item.Id)}>
                <Icon name='md-information-circle-outline' />

              </TouchableOpacity>
              <TouchableOpacity style={[styles.backRightBtn, styles.backRightBtnRight]} onPress={this.deleteItem(data.item.Id)}>
              <Icon name='trash-outline' />

              </TouchableOpacity>
            </View>
          )}
          leftOpenValue={90}
          rightOpenValue={-150}
          onEndReached={this.handleLoadMore}
          onEndReachedThreshold={0.5}
          initialNumToRender={8}
          ItemSeparatorComponent={this.renderSeparator}
          ListFooterComponent={this.renderFooter}
          onRefresh={this.handleRefresh}
          refreshing={this.state.refreshing}
        />
        <ActionSheet  ref={(c) => { this.actionSheet = c; }} />
      </View>
    );
  }
}

export default App

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    flex: 1,
    //paddingTop: 50,
  },
  backTextWhite: {
    color: '#FFF'
  },
  rowFront: {
    alignItems: 'center',
    backgroundColor: '#CCC',
    justifyContent: 'center',
  },
  rowBack: {
    alignItems: 'center',
    backgroundColor: 'green',
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingLeft: 15,
  },
  backRightBtn: {
    alignItems: 'center',
    bottom: 0,
    justifyContent: 'center',
    position: 'absolute',
    top: 0,
    width: 75
  },
  backRightBtnLeft: {
    backgroundColor: 'blue',
    right: 75
  },
  backRightBtnRight: {
    backgroundColor: 'red',
    right: 0
  },
});

The list works properly and comes data but whenever I scroll down or up it doesn't work anymore. Please help me

If you are in mindset to change your package, then you can try react-native-snap-carousel, perfect for your requirement. Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM