Как динамически применять разные стили для сопоставления текста из динамического абзаца в React Native - PullRequest
0 голосов
/ 19 сентября 2019

Я занимаюсь проектом React Native.Это мой первый проект в React Native.И я получаю вопросы и ответы в этом (несколько вопросов и ответов).

Каждый ответ имеет несколько разных стилей с совпадающим текстом параграфа ответа.Если есть какой-либо соответствующий текст, я должен применить эти стили к выбранным текстам. Могут быть разные стили шрифта, подчеркивание, URL-ссылка, электронные письма.

Я пробовал использовать следующий код, но он отображается пустымdata.

text: the text to search for in the answer's text 
instance: the instance to match in case of multiple instances found within the text (if zero is provided, match all instances)
link: this can be a url or a mailto to use for the matched text  
styles: a collection of styles to be applied to the matching text

 Json Response is following
 {
    "question": "How do I change my pwd?",
    "answer": "To change your pwd, go to the Settings section from the main menu and choose the Change Password option. The new password will be your new  password, as well. Still having difficulty logging in? Please contact the Services Team would be great.",

 "format": [
      {
        "text": "Settings",
        "instance": 1,
        "link": "",
        "styles": {
          "fontWeight": "bold"
        }
      },

      {
        "text": "Change Password",
        "instance": 1,
        "link": "",
        "styles": {
          "fontWeight": "bold"
        }
      },

      {
        "text": "Services Team",
        "instance": 1,
        "link": "mailto:client@gmail.com",
        "styles": {
          "fontStyle": "underline",
          "color": "blue"
        }
      }

    ]

  }

Возможно, есть ключ форматирования или его нет.Но, если этот ключ существует, я должен применить разные стили для сопоставления данных для данных ответа / вопроса.Даже если есть почтовый идентификатор, там, я должен показать подчеркивание, как только нажмите на это, он должен открыть электронную почту.Если есть какой-либо URL-адрес, похожий на веб-сайт, он должен открыть веб-сайт при его нажатии.

Я показываю эти данные в Плоский список

export default class Cell extends PureComponent {
    state = {
      isSelected: false,
    }

    formatedContent = (format, label) => {
      let managebleLabel = label; // initialize the working text
      format.map((item) => {
        const { styles, link, text } = item;
        console.log('item', item);
        const indexOfText = managebleLabel.indexOf(text); // Get the index of our text
        const workingLabel = managebleLabel.substring(0, indexOfText + text.length); // Get complete working label with our text to format
        managebleLabel = managebleLabel.split(text)[1]; // This is the left label we are going to work with next
        const splittedLabel = workingLabel.split(text); // on position 0 we get the label with no format and on position 1 our text to format
        const simpleLabel = <Text>{splittedLabel[0]}</Text>; // create the element
        const formatedLabel = link && link.length > 0 ? (
          this.isLink(text, link, styles)
        ) : (
          <Text style={typeof styles === Object ? styles : {}}>{text}</Text>
        ); // Assign the format to label
        return (
          <Text>
            {simpleLabel}
            {formatedLabel}
          </Text>
        ); // Join the labels
      });
    };

    isLink = (label, link, style) => {
      return (
        <TouchableOpacity
          onPress={() => Linking.openURL(link)}
          style={typeof style === Object ? style : {}}
        >
          <Text>{label}</Text>
        </TouchableOpacity>
      );
    }

    onPress = () => {
      const { index, onHeaderSelected, item } = this.props;
      this.setState(prevState => ({
        isSelected: !prevState.isSelected,
      }));
    }

    render() {
      const { isSelected } = this.state;
      const { item } = this.props;
      const answer = get(faqjson, 'answer');
      const formatText = get(faqjson, 'format');    
      return (
        <View style={styles.container}>
          <TouchableWithoutFeedback onPress={this.onPress}>
            <View style={styles.questionContainer}>
              <Text style={styles.question}>{item.question}</Text>
              <Image source={isSelected ? res.images.arrow_up : res.images.arrow_down} style={styles.image} />
            </View>
          </TouchableWithoutFeedback>
          {isSelected && (
          <View style={styles.answerContainer}>
            <Text style={[styles.answer]} ellipsizeMode="tail">
              {this.formatedContent(formatText, get(faqjson, 'answer'))}
            </Text>
          </View>
          )
        }
        </View>
      );
    }
}

Но, он показываетпустые данные после сопоставления.Есть предложения?

...