SectionList中项目的索引为null

时间:2019-06-16 11:32:15

标签: react-native react-native-sectionlist

我是本机反应的新手。我想从数组中删除元素,为此,我尝试使用项目索引。我看到了一个示例,其中renderItem接收了索引,但是我在renderItem中获得的索引为null的问题。

<SectionList                  
                renderItem={({item, index}) => {
                  Alert.alert(index); // here the index is null
                  return (
                    <SectionListItem  item={item} index={index} parentSectionList={this}>
                    </SectionListItem>);
                }}
                sections={this.state.contacts.sort((a, b) => a.title < b.title ? -1 : 1)}
              />

实际删除项目的方法。如果我设置默认索引,则可以正常工作

removeItem = (deletedKey) => {
    this.setState({
     deletedRowKey : deletedKey,
     // here I want to remove my item with deletedKey = index, but deletedKey is null
     contacts: this.state.contacts.splice(1), // works, removing the 1st item from array
    });
  }

这是我数组中的项目的样子:

const newContact = {
      title: this.state.contactName.charAt(0), 
      data: [{
        name: this.state.contactName, 
        phone: this.state.contactPhone
        }]};

我的完整代码。我的错误在哪里?

import React, { Component } from 'react';
import { StyleSheet , View , SectionList, Text, Button, Modal,TouchableHighlight, Alert, TextInput} from 'react-native';
import { Icon } from 'react-native-elements';
import DialogInput from 'react-native-dialog-input';
import Swipeout from 'react-native-swipeout';

class SectionListItem extends Component {
    constructor(props) {
          super(props);
      this.state = {
        activeRowKey: null // saved the key of deleting object
      }        
    }

  render() {
    const swipeSettings = {
      autoClose: true,
      onClose: (secId, rowId, direction) => {
        this.setState({activeRowKey : null});
      },
      onOpen: (secId, rowId, direction) => {
        this.setState({activeRowKey : this.props.item.name});
      },
      right: [
        {
          onPress: () => {
            this.props.parentSectionList.refreshSectionList(this.props.item.name)
          },
          text: 'Delete', type: 'delete'
        }
      ],
      rowId: this.props.index,
      sectionId: 1
    };

    return (
      <Swipeout {...swipeSettings} style={{backgroundColor:'white'}}>
        <View style={styles.contactItem}>
           <View>
            <Text style={{fontSize: 19, fontWeight: 'bold', paddingLeft:10}}>{this.props.item.name}</Text>
            <Text style={{fontSize: 17, paddingLeft:10}}>{this.props.item.phone}</Text>
            <Text style={{fontSize: 15, paddingLeft:10}}>{this.props.item.address}</Text>
          </View>
            <View style={{margin: 8}}>
              <Icon name="heartbeat" type='font-awesome' size={30} color='black' 
                onPress={()=>{this.props.parentSectionList.addFavorites(this.props.section)}}/>
            </View>           
      </View>
      </Swipeout>

    );
  }
}

export default class Contacts extends React.Component {

  constructor(props) {
    super(props);   

    this.state = {
      contacts : [],
      favorites: [],
      newContactDialogVisible: false,
      name : '',
      phone : '',
      address: '',
      showNoContactsMsg: true,
      deletedRowKey: null
    }
  }

  static navigationOptions = {
    title: 'Contacts',
    tabBarIcon: ({tintColor}) => (
          <Icon name="phone" size={30} color={tintColor} />
        )
  };

  refreshSectionList = (deletedKey) => {
    this.setState({
     deletedRowKey : deletedKey,
     contacts: this.state.contacts.splice(deletedKey),
    });
  }

  refreshContactsList = () => {
    const newContact = {
      title: this.state.name, 
      data: [{
        name: this.state.name, 
        phone: this.state.name
        }]};
    this.setNewContactModalVisiblity(false);
    this.setState({ contacts: [...this.state.contacts, newContact]});
    if(this.state.contacts.length > 0) 
    {
       this.setState({ showNoContactsMsg: false });
    }
    else 
    {
      this.setState({ showNoContactsMsg: true });
    } 

    this.setState({ name: '' });
    this.setState({ phone: '' });
  }

  addFavorites = (section) => {
    this.setState({ favorites: [...this.state.favorites, section]});
  }

  searchGooglePlaces(address) {
    const key = 'contactsiliya';
    const url = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=' + address; +
      '&inputtype=textquery&key=' + key
    fetch(url, {

    method: 'GET'
    })
    .then((response) => response.json())
    .then((responseJson) => {
        Alert.alert(JSON.stringify(responseJson));
        this.setState({address:JSON.stringify(responseJson)})
    })
    .catch((error) => {
        console.error(error);
    });
  }

  goToFavorites = () => {
    this.props.navigation.navigate("Favorites")
  };

  setNewContactModalVisiblity(visible) {
    this.setState({newContactDialogVisible: visible});
  }

  render() {
    return (
      <View style={{flex: 1}}>
        <View>
          <Modal   // new contact dialog
            animationType="slide"            
            transparent={true}
            visible={this.state.newContactDialogVisible}>
            <View style={{flex: 1, justifyContent:'center', alignItems:'center'}}>
              <View style={styles.newContactView}>
                <TextInput
                  style={styles.textInput}
                  placeholder="Name"
                  onChangeText={(text) => this.setState({name:text})}/>
                <TextInput
                  style={styles.textInput}  
                  keyboardType = 'number-pad'                
                  placeholder="Phone"
                  onChangeText={(text) => this.setState({phone:text})}/>
                <TextInput
                  style={styles.textInput}                  
                  placeholder="Address"
                  onChangeText={(text) => this.searchGooglePlaces(text)}/>

                  <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>                  
                    <Button onPress={this.refreshContactsList} title="Save Contact"/> 
                  </View>                
                </View>
            </View>
          </Modal>
      </View>

        <View style={styles.addContact}>
          <Button title="+ New Contact"
                  onPress={() => {
                    this.setNewContactModalVisiblity(true);
                  }}>          
          </Button>
        </View>

        <View style={{flex:7}}>
          <View>
            <SectionList                  
                renderItem={({item, index}) => {
                  return (
                    <SectionListItem  item={item} index={index} parentSectionList={this}>
                    </SectionListItem>);
                }}
                sections={this.state.contacts.sort((a, b) => a.title < b.title ? -1 : 1)}
              />
          </View>
          {this.state.showNoContactsMsg ? (  // not show the view if there are contacts on the screen
          <View style={{alignItems: 'center', marginTop:200}} >
            <Text>No contacts yet</Text>            
          </View> 
          ) : null}         
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  addContact: {
    flex:0.5,
    marginTop:27
  },
  newContactView: {
    width: 300,
    height: 300,
    borderRadius:10,
    padding:10,
    borderWidth: 3,
    borderColor: '#2196f3',
    backgroundColor: '#ecf0f1'
  },
  textInput: {
    height: 45, 
    borderBottomWidth: 1, 
    borderColor: '#999799',
    paddingLeft:5, 
    margin: 10,
    fontSize:17
  },
  contactItem: {
    flex:1, 
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginLeft: 10, 
    marginRight: 10,
    marginBottom: 10,
    borderWidth: 2, 
    borderColor: 'grey', 
    borderRadius: 10,
  }
});

0 个答案:

没有答案