React-Native Накопить результаты от al oop до одной строки - PullRequest
0 голосов
/ 20 февраля 2020

Я хочу извлечь данные между тегом и, основываясь на содержимом, вернуть <View><Text>This is a Text</Text></View> или <View><Text>This is a Picture</Text></View>

Проблема в том, что я не знаю, как накапливать результат из соответствует Article, а затем возвращает {Article} в качестве окончательного результата.

В приведенном ниже случае я должен получить такой рендер:

<View><Text>This is a Text</Text></View>
<View><Text>This is a Picture</Text></View>
<View><Text>This is a Text</Text></View>

Вместо этого я получу окончательный результат , Я пытался Article = Article + <View><Text>This is a Text</Text></View> и Article += <View><Text>This is a Text</Text></View>, но оба они не удалось.

export default class App extends React.Component {
  render() {

let pattern = /<RNVW>(.*?)<\/RNVW>/g;
let str =   '<RNVW><p>Markets are mixed in Asia, with Japan\'s benchmark slipping 0.7% after the government reported the economy contracted in the last quarter</em></p><p>BANGKOK -- Markets were mixed in Asia on Monday, with Japan\'s benchmark slipping 0.7% after the government reported the economy contracted 6.3% in annual terms in the last quarter. China\'s shares got a boost after the central bank stepped in to help the economy with a rate cut, extra buying of securities and tax cuts. </p><p>The Nikkei 225 in Tokyo closed at 23,523.24, while Sydney\'s S&P ASX/200 edged 1% lower to 7,125.10.</p></RNVW><RNVW><img src="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/04/1493235373large_react_apps_A-01.png"></RNVW><RNVW><p>Such moves will likely be followed by still more, said Julian Evans-Pritchard, given that many of the companies worst affected by the virus outbreak are smaller ones that lack access to loans from major state-run banks. </p><p>The government has also announced plans for tax cuts and other measures to help companies struggling with shut-downs of cities and plunging consumer spending and travel. </p><p>"We think the PBOC will need to expand its re-lending quotas and relax constraints on shadow banking in order to direct more credit to struggling SMEs," Evans-Pritchard said in a commentary. </p><p>Wall Street closed out a wobbly day of trading Friday with the major stock indexes notching their second straight weekly gain. Though trading was mostly subdued and cautious following China\'s report Thursday of a surge in cases of a new virus that raised fresh concerns about global economic growth.</p></RNVW>';

    let match;
    let Article; 
    while ((match = pattern.exec(str)) !== null) {
      if (match[1].startsWith("<p>") !== false) {
       Article = (
        <View><Text>This is a Text</Text></View>
        );
      } else {
      Article = (
           <View><Text>This is a Picture</Text></View>
        );
      }
    }

    return (
      <View style={styles.container}>
     {Article}
      </View>
    );
  }
}

1 Ответ

3 голосов
/ 20 февраля 2020

Привет, Винсент

вы допустили одну ошибку с Артикулом , вы пытаетесь назначить новый элемент для Артикула каждый раз вместо этого Вы должны go с массивом и pu sh новыми элементами каждый раз в массиве .

Внести некоторые изменения в свой код:

class App extends Component {

articleView = () => {

let pattern = /<RNVW>(.*?)<\/RNVW>/g;
let str ="<RNVW><p>Markets are mixed in Asia, with Japan's benchmark slipping 0.7% after the government reported the economy contracted in the last quarter</em></p><p>BANGKOK -- Markets were mixed in Asia on Monday, with Japan's benchmark slipping 0.7% after the government reported the economy contracted 6.3% in annual terms in the last quarter. China's shares got a boost after the central bank stepped in to help the economy with a rate cut, extra buying of securities and tax cuts. </p><p>The Nikkei 225 in Tokyo closed at 23,523.24, while Sydney's S&P ASX/200 edged 1% lower to 7,125.10.</p></RNVW><RNVW><img src=\"https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/04/1493235373large_react_apps_A-01.png\"></RNVW><RNVW><p>Such moves will likely be followed by still more, said Julian Evans-Pritchard, given that many of the companies worst affected by the virus outbreak are smaller ones that lack access to loans from major state-run banks. </p><p>The government has also announced plans for tax cuts and other measures to help companies struggling with shut-downs of cities and plunging consumer spending and travel. </p><p>\"We think the PBOC will need to expand its re-lending quotas and relax constraints on shadow banking in order to direct more credit to struggling SMEs,\" Evans-Pritchard said in a commentary. </p><p>Wall Street closed out a wobbly day of trading Friday with the major stock indexes notching their second straight weekly gain. Though trading was mostly subdued and cautious following China's report Thursday of a surge in cases of a new virus that raised fresh concerns about global economic growth.</p></RNVW>";

let match;
let Article = [];
while ((match = pattern.exec(str)) !== null) {
  if (match[1].startsWith("<p>") !== false) {
    Article.push(
      <View>
        <Text>This is a Text</Text>
      </View>
    );
  } else {
    Article.push(
      <View>
        <Text>This is a Picture</Text>
      </View>
    );
  }
}
return Article;

};
render() {
  return (
   <View>
    {this.articleView()}
  </View>
  );
 }
}

это даст вам желаемый результат:)

Я надеюсь, это то, что вы искали!

Спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...