Как выбрать элемент в ListView с заголовками разделов React Native

Я должен иметь возможность щелкнуть элемент и поставить галочку напротив него. Я пытаюсь реализовать сгруппированные контакты с заголовками разделов, для которых заданы буквы алфавита. С помощью простого списка (без заголовков разделов) я могу выбрать контакт, но я не могу заставить его работать с заголовком раздела.

class ContactsView extends React.Component{
  constructor(props) {
    super(props);
    this.checkContact = this.checkContact.bind(this);
    this.renderSectionHeader =  this.renderSectionHeader.bind(this);
    this.toArray = this.toArray.bind(this);

    let contacts = this.props.contacts || [];
    let ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2
    });
    this.state = {
      contacts:contacts,
      dataSource:ds
    }
  }

  componentDidMount() {
    ToastAndroid.show('Component will did mount', ToastAndroid.SHORT);
    this.setState({
      dataSource: this.state.dataSource.cloneWithRowsAndSections(this.state.contacts)
    });
  }

  componentWillMount(){
    //Clear the selected invitees.
    ToastAndroid.show('Component contacts did mount', ToastAndroid.SHORT);
  }

  componentWillUpdate(){
    //Check if there are selected contacts and update invitees.
    //this.invitees = this.getInvitees();
    ToastAndroid.show('Component will update', ToastAndroid.SHORT);
  }

  onLoadMore(){
    return;
  }

  renderContact(item,sectionID, rowID){
    let icon = <Icon name="check-box-outline-blank" size={25} style={styles.checkIcon} color="#83D8F8" />;

    if(item.checked)
      icon = <Icon name="check-box" size={25} style={styles.checkIcon} color="#4ABF30" /> 

    let avatar = <Image styleName="small-avatar" style={styles.avatar} source={{uri: item.thumbnailPath}} />
    if(!item.thumbnailPath){
      avatar = <MaterialInitials style={styles.avatar} backgroundColor={item.color} color={'white'} size={40} text={item.fullName} single={false} />
    }

    if(rowID === 0){
      styles.caption['borderTopColor'] = '#fff';
    }

    //let itemIndex = 
    console.log(item.checked)
    return (
      <TouchableHighlight onPress={() => this.checkContact(item,sectionID,rowID)}>
        <Row style={styles.itemRow}>
          {icon}
          {avatar}
          <View styleName="vertical" style={styles.caption}>
            <Subtitle styleName="bold multiline" style={styles.itemTitle}>{item.fullName}</Subtitle>
            <Caption style={styles.itemPhone}>{item.phone}</Caption>
          </View>
        </Row>
      </TouchableHighlight>
    )
  }

  renderSectionHeader(sectionData, sectionID){
    return (
      <View key={sectionID} style={{marginTop:0,marginBottom:0,paddingBottom:0,paddingTop:0}}>
        <Text style={{fontFamily:'Cabin_Bold',fontSize:20,color:'#1d313c',marginLeft:11,marginBottom:10,marginTop:10}}>
          {sectionID}
        </Text>
      </View>
    ) 
  }

  checkContact(item,sectionID,id){

    let dataClone = Object.assign({},this.state.contacts);
    dataClone[sectionID][id] = { ...dataClone[sectionID][id], checked: !item.checked }

    this.setState({
      contacts: dataClone,
      dataSource:this.state.dataSource.cloneWithRowsAndSections(dataClone)
    });
    console.log(this.state.contacts);
    //this.props.dispatch(ContactsState.check(sectionID,id,item));
  }

  toArray(_Object){
   let _Array = new Array();
    for(let name in _Object){
      _Array[name] = _Object[name];
    }
   return _Array;
  }

  render() {


    return (
      <ListView 
        style={{marginBottom:0,marginTop:0,paddingBottom:0,paddingTop:0}}
        dataSource ={this.state.dataSource} 
        renderSectionHeader={this.renderSectionHeader}
        initialListSize={1}
        pageSize={10}
        scrollRenderAheadDistance ={360}
        renderRow={this.renderContact.bind(this)}
      />
    );
  }
}

export default ContactsView;

Я должен иметь возможность щелкнуть элемент и установить его флажок.


person kabangi julius    schedule 21.02.2017    source источник
comment
вы имеете в виду, вы хотели сделать заголовки разделов кликабельными кнопками?   -  person Ata Mohammadi    schedule 21.02.2017
comment
Неа. Я хочу иметь возможность выбрать элемент в списке и проверить его   -  person kabangi julius    schedule 21.02.2017


Ответы (1)


Простой пример:

import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, TouchableOpacity } from 'react-native';

class ListViewBasics extends Component {
  // Initialize the hardcoded data
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows([
        {
          id: 1,
          title: 'title1'
        },
        {
          id: 2,
          title: 'title2'
        },
        {
          id: 3,
          title: 'title3'
        },
      ]),
      checkedItems: {}
    };
  }
  checkMark(rowId){
    let marked = this.state.checkedItems;
    if(market.hasOwnProperty(rowId)){
     if(marked[rowId]){
      marked[rowId] = false;
     } else {
      marked[rowId] = true;
     }
    } else {
      marked[rowId] = true;
    }
    this.setState({checkedItems: marked})
  }
  renderCheckMark(rowId){
    let marked = this.state.checkedItems;
    if(marked.hasOwnProperty(rowId)){
      if(market[rowid]){
       return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
  renderItem(rowData){
    <TouchableOpacity
      onPress={()=>{
        this.checkMark(rowData.id)
      }}
    >
      <Text>{rowData.title} {this.renderCheckMark(rowData.id) ? 'X' : null}</Title>
    </TouchableOpacity>
  }
  render() {
    return (
      <View style={{flex: 1, paddingTop: 22}}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(rowData) => { this.renderItem(rowData) }}
        />
      </View>
    );
  }
}

// App registration and rendering
AppRegistry.registerComponent('ListViewBasics', () => ListViewBasics);

Если элемент выбран, после заголовка строки будет отображаться «X».

person Ata Mohammadi    schedule 21.02.2017