Как отобразить элементы во вложенном массиве в отдельных строках в реагировать нативно? - PullRequest
1 голос
/ 14 октября 2019

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

Например, если для контакта 'x' сохранено 5 номеров, я хотел бы иметь пять строк под именем 'x', но с разными телефонными номерами.

это мой render () в App.js:

render() {
   return (
         {this.state.contacts.map(contact => {
            return (
              <ListItem
                key={contact.recordId}
                title={`${contact.givenName} ${
                  contact.familyName}`}
                description={contact.phoneNumbers.map(phone => (
                  <Text style={styles.phones}>
                    {phone.number} -
                  </Text>
                ))}
              />
            );
          })}

, а вот ListItem.js:

import PropTypes from 'prop-types';
import {RectButton} from 'react-native-gesture-handler';
import Swipeable from 'react-native-gesture-handler/Swipeable';

class ListItem extends Component {
  static propTypes = {
    leftElement: PropTypes.element,
    title: PropTypes.string,
    description: PropTypes.string,
    rightElement: PropTypes.element,
    rightText: PropTypes.string,
    onPress: PropTypes.func,
    onDelete: PropTypes.func,
    onLongPress: PropTypes.func,
    disabled: PropTypes.bool,
  };

  renderRightAction = (iconName, color, x, progress) => {
    const trans = progress.interpolate({
      inputRange: [0, 1],
      outputRange: [x, 0],
    });

    const pressHandler = () => {
      const {onDelete} = this.props;
      if (onDelete) onDelete();
      this.close();
    };

    return (
      <Animated.View style={{flex: 1, transform: [{translateX: trans}]}}>
        <RectButton
          style={[styles.rightAction, {backgroundColor: color}]}
          onPress={pressHandler}>
          <Text style={{color: '#fff'}}>Delete</Text>
        </RectButton>
      </Animated.View>
    );
  };

  renderRightActions = progress => (
    <View style={{width: 64, flexDirection: 'row'}}>
      {this.renderRightAction('trash', '#ef5350', 64, progress)}
    </View>
  );

  renderRightActions = progress => (
    <View style={{width: 64, flexDirection: 'row'}}>
      {this.renderRightAction('trash', '#ef5350', 64, progress)}
    </View>
  );

  updateRef = ref => {
    this.swipeableRow = ref;
  };

  close = () => {
    this.swipeableRow.close();
  };

  render() {
    const {
      leftElement,
      title,
      description,
      rightElement,
      rightText,
      onPress,
      onLongPress,
      disabled,
    } = this.props;

    const Component = onPress || onLongPress ? TouchableHighlight : View;

    const {
      itemContainer,
      leftElementContainer,
      rightSectionContainer,
      mainTitleContainer,
      rightElementContainer,
      rightTextContainer,
      titleStyle,
      descriptionStyle,
    } = styles;

    return (
      <Swipeable
        ref={this.updateRef}
        friction={1}
        renderRightActions={this.renderRightActions}>
        <Component
          onPress={onPress}
          onLongPress={onLongPress}
          disabled={disabled}
          underlayColor="#f2f3f5">
          <View style={itemContainer}>
            {leftElement ? (
              <View style={leftElementContainer}>{leftElement}</View>
            ) : (
              <View />
            )}
            <View style={rightSectionContainer}>
              <View style={mainTitleContainer}>
                <Text style={titleStyle}>{title}</Text>
                {description ? (
                  <Text style={descriptionStyle}>{description}</Text>
                ) : (
                  <View />
                )}
              </View>
              <View style={rightTextContainer}>
                {rightText ? <Text>{rightText}</Text> : <View />}
              </View>

              {rightElement ? (
                <View style={rightElementContainer}>{rightElement}</View>
              ) : (
                <View />
              )}
            </View>
          </View>
        </Component>
      </Swipeable>
    );
  }
}
...
export default ListItem;

Любая помощь будет принята с благодарностью.

1 Ответ

0 голосов
/ 16 октября 2019

Для тех, кто ищет ответ, я понял это с помощью вложенного цикла for, сделал копию каждого контакта, который имел более одного номера телефона, и вставил его в основной объект контактов:

 updateContacts(contact) {
    let reg = /(0|\+98)?([ ]|,|-|[()]){0,2}9[0|1|2|3|4]([ ]|,|-|[()]){0,2}(?:[0-9]([ ]|,|-|[()]){0,2}){8}/;

    for (let i = 0; i < contact.length; i++) {
      if (contact[i].phoneNumbers.length > 1) {
        let s = contact[i].phoneNumbers.length;
        this.setState({flag:false})

        for (let size = 0; size < s; size++) {
          let a = JSON.parse(JSON.stringify(contact));
          a[i].phoneNumbers = [contact[i].phoneNumbers[size]];

          if (reg.test(a[i].phoneNumbers[0].number)) {
            contact.splice(i, 0, a[i]);
            i = i + 1;
            this.setState({flag:true})

          }
        }
        if (this.state.flag) {
          contact.splice(i, 1);
          i = i - 1;
        }
      }
    }
    this.forceUpdate();
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...