Как показать для текста Больше / Меньше в React-Naitve (Javascript) - PullRequest
0 голосов
/ 23 апреля 2019

Я занимаюсь разработкой реактивного приложения. В этом мы показываем некоторое описание на текст , это может быть количество строк.

Итак, если данные имеют более 3 строк, я должен показать Больше и Меньше, если они расширены.

        <FlatList
          style={styles.faltList}
          showsVerticalScrollIndicator
          data={data}
          extraData={this.state}
          renderItem={({ item, index }) => (
            <View style={styles.flatListCell}>
                <Text style={styles.description}>{item.description}</Text>
              </View>
            </View>
          )
          }
          ItemSeparatorComponent={() => (
            <View style={{ height: 10}} />
          )}
        />

Я нашел библиотеку Reaction-native-view-more-text , но я хотел бы реализовать ее с помощью специального кода.

Примечание. Я отображаю этот текст в Flatlist.

Есть предложения?

Ответы [ 2 ]

1 голос
/ 23 апреля 2019

Вы можете просто использовать numberOfLines, то есть <Text> prop:

Используется для усечения текста с помощью многоточия после вычисления текстового макета, включая перенос строки, так что общееколичество строк не превышает это число.

И, очевидно, адекватный логический обработчик для сохранения в вашем state того, какой текст показан, а какой урезан.

Давайте посмотримпример, который я только что создал:

state = {
    textShown: -1,
  };

  toggleNumberOfLines = index => {
    this.setState({
      textShown: this.state.textShown === index ? -1 : index,
    });
  };

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={[
            { key: 'a', description: longText },
            { key: 'b', description: longText },
            { key: 'c', description: longText },
          ]}
          renderItem={({ item, index }) => (
            <View style={styles.flatListCell}>
              <Text
                numberOfLines={this.state.textShown === index ? undefined : 3}
                style={styles.description}>
                {longText}
              </Text>
              <Text
                onPress={() => this.toggleNumberOfLines(index)}
                style={{ color: 'red' }}>
                {this.state.textShown === index ? 'read less...' : 'read more...'}
              </Text>
            </View>
          )}
        />
      </View>
    );
  }

Здесь я использую state, чтобы сохранить индекс элемента в показанном FlatList.Если ничего не отображается, то сохраненное значение равно -1.

Вы можете попробовать его поведение в этой закуске, которая (я надеюсь) воспроизводит ваш случай.Дайте мне знать, если это то, что вы ищете.(Привет, Анилкумар, мы уже встретились :))

0 голосов
/ 23 апреля 2019
import React from 'react';
import PropTypes from 'prop-types';
import AnchorText from '../AnchorText';

import { StyledContainer, RegularText } from './styles';

export default class Description extends React.Component {
      constructor(props) {
super(props);
this.state = {
  showMore: true,
};
}

 onClick = () => {
this.setState({
  showMore: false,
});
};

 render() {
const { description } = this.props;
const { showMore } = this.state;
if (!description) return null;

return (
  <StyledContainer FD={'column'}>
    {showMore ? (
      <RegularText MT={1}>
        {description.slice(0, 150)}{' '}
        {description.length > 150 && (
          <AnchorText onClick={this.onClick} label=" .. Read more" />
        )}{' '}
      </RegularText>
    ) : (
        <RegularText MT={1}>{description}</RegularText>
    )}
  </StyledContainer>
);
 }
} 

Description.propTypes = {
 description: PropTypes.string,
 };

Проверить этот виджет

...