如何在React Naitve(Javascript)中显示更多/更少的文本

如何在React Naitve(Javascript)中显示更多/更少的文本,javascript,react-native,text,react-native-flatlist,Javascript,React Native,Text,React Native Flatlist,我正在开发react本机应用程序。在这里,我们展示了一些关于文本的描述,可能是行数 所以,如果数据有超过3行,我必须显示更多和更少,如果它被扩展 <FlatList style={styles.faltList} showsVerticalScrollIndicator data={data} extraData={this.state} renderItem={({ ite

我正在开发react本机应用程序。在这里,我们展示了一些关于文本的描述,可能是行数

所以,如果数据有超过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}} />
          )}
        />
(
{item.description}
)
}
ItemSeparatorComponent={()=>(
)}
/>
我发现react native view更多文本库,但我想通过自定义代码实现它

注意:我正在平面列表中显示该文本

有什么建议吗?

从“React”导入React;
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,
 };
从“道具类型”导入道具类型; 从“../AnchorText”导入AnchorText; 从“./styles”导入{StyledContainer,RegularText}; 导出默认类描述扩展React.Component{ 建造师(道具){ 超级(道具); 此.state={ 肖莫尔:没错, }; } onClick=()=>{ 这是我的国家({ 肖莫尔:错, }); }; render(){ const{description}=this.props; const{showMore}=this.state; 如果(!description)返回null; 返回( {showMore( {description.slice(0150)}{'} {description.length>150&&( )}{' '} ) : ( {说明} )} ); } } Description.propTypes={ description:PropTypes.string, };

查看此小部件

您只需使用
numberOfLines
,这是一个
道具:

用于在计算文本后用省略号截断文本 布局,包括换行,使总行数 不超过这个数字

显然,还需要一个足够的逻辑处理程序来保存
状态中显示的文本和截断的文本

让我们看一个我刚刚创建的示例:

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>
    );
  }
状态={
文本显示:-1,
};
Togglenumberofline=索引=>{
这是我的国家({
textShowed:this.state.textShowed==索引?-1:index,
});
};
render(){
返回(
(
{longText}
this.togglenumberofline(index)}
样式={{color:'red'}}>
{this.state.textShowed==索引?'read less…':'read more…'
)}
/>
);
}
这里我使用
state
将元素的索引保存在所示的
FlatList
中。如果未显示任何值,则保存的值为-1

你可以在零食中尝试它的行为,(我希望)复制你的情况。 如果这是你要找的,请告诉我。
(嗨,阿尼尔库玛,我们已经见过面了:)

我试过这样做,希望对你和其他人有所帮助

const postTextContent=(道具)=>{
const[textShowed,settextShowed]=useState(false);//显示剩余文本
const[lengthMore,setLengthMore]=useState(false);//显示“读取更多和更少行”
const toggleNumberOfLines=()=>{//切换显示文本或隐藏文本
SettextShowed(!textShowed);
}
const onTextLayout=useCallback(e=>{
setLengthMore(e.nativeEvent.lines.length>=4);//检查文本是否超过4行
//控制台日志(例如nativeEvent);
},[]);
返回(
{你的长文本}
{
lengthMore?{textShowed?'Read less…':'Read more…'}
:null
}
)
}

第一个实现已接近尾声,但问题是,当文本等于3行时,“阅读更多”按钮会显示,但由于没有更多文本,因此不应显示。我通过更新状态中的行数以及检查文本是否已显示来修复它

const ReadMoreText = ({ readMoreStyle, text, textStyle }) => {
  const [showMoreButton, setShowMoreButton] = useState(false);
  const [textShown, setTextShown] = useState(false);
  const [numLines, setNumLines] = useState(undefined);

  const toggleTextShown = () => {
    setTextShown(!textShown);
  };

  useEffect(() => {
    setNumLines(textShown ? undefined : 3);
  }, [textShown]);

  const onTextLayout = useCallback(
    (e) => {
      if (e.nativeEvent.lines.length > 3 && !textShown) {
        setShowMoreButton(true);
        setNumLines(3);
      }
    },
    [textShown],
  );

  return (
    <>
      <Text onTextLayout={onTextLayout} numberOfLines={numLines} style={textStyle} ellipsizeMode="tail">
        {text}
      </Text>

      {showMoreButton ? (
        <Text onPress={toggleTextShown} style={readMoreStyle}>
          {textShown ? 'Read Less' : 'Read More'}
        </Text>
      ) : null}
    </>
  );
};
const ReadMoreText=({readMoreStyle,text,textsyle})=>{
const[showMoreButton,setShowMoreButton]=使用状态(false);
const[textShowed,settextShowed]=useState(false);
const[numLines,setNumLines]=useState(未定义);
const toggleTextShowed=()=>{
SettextShowed(!textShowed);
};
useffect(()=>{
setNumLines(文本显示?未定义:3);
},[文本显示];
const onTextLayout=useCallback(
(e) =>{
如果(e.nativeEvent.lines.length>3&&!文本显示){
设置ShowMore按钮(真);
setNumLines(3);
}
},
[文本显示],
);
返回(
{text}
{showMoreButton(
{textShowed?'Read Less':'Read More'}
):null}
);
};
状态={ textLenth:null, 行数:3, }

})

this.handleSeeMore()}
ellipsizeMode=“中间”
onTextLayout={({nativeEvent:{lines}}})=>
this.setState({textLenth:lines.length==3})
}>
本次演出让我们一窥我们艺术作品的展示:
现代时尚标志艺术作品LKJFKLJF ksnfksfnsf吉祥物&
定制标志efdfg艺术品:lk knnk“探索
终极体验为了满足您的设计需求,请让我们
以图形显示您的。。。!!为什么是Stratinit团队?我们相信自己的信念
{'                      '}
{this.state.textLenth&&(
this.setState({numberOfLines:0})}>
查看更多
)}

看看我的解决方案,我没有使用文本行,而是使用了文本长度

import React, {useState} from 'react';
import {Text, View, Image, TouchableOpacity, StyleSheet} from 'react-native';

const PostContent = () => {
  const postDescription =
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
  const [showMore, setShowMore] = useState(false);

  return (
    <View style={styles.postContentContainer}>
      {postDescription.length > 120 ? (
        showMore ? (
          <TouchableOpacity onPress={() => setShowMore(!showMore)}>
            <Text style={styles.postDescription}>{postDescription}</Text>
            <Text style={styles.seeMore}>Show less</Text>
          </TouchableOpacity>
        ) : (
          <TouchableOpacity onPress={() => setShowMore(!showMore)}>
            <Text style={styles.postDescription}>
              {`${postDescription.slice(0, 120)}... `}
            </Text>
            <Text style={styles.seeMore}>Show more</Text>
          </TouchableOpacity>
        )
      ) : (
        <Text style={styles.postDescription}>{postDescription}</Text>
      )}
    </View>
  );
};

export default PostContent;

const styles = StyleSheet.create({
  postContentContainer: {
    // borderWidth: 1,
    // borderColor: 'red',
    flexDirection: 'column',
  },

  postMedia: {
    //borderWidth: 1,
    //borderColor: 'red',
    width: '100%',
    height: 280,
    resizeMode: 'cover',
  },

  postDescription: {
    paddingTop: 15,
    paddingHorizontal: 15,
    color: colors.text.black,
    fontFamily: fonts.family.body,
    fontSize: fonts.fontSizes.button,
    fontWeight: fonts.fontWeights.thin,
  },

  seeMore: {
    paddingHorizontal: 15,
    color: colors.text.grey,
    fontStyle: 'italic',
    textDecorationLine: 'underline',
    fontFamily: fonts.family.body,
    fontSize: fonts.fontSizes.button,
    fontWeight: fonts.fontWeights.thin,
  },
});
import React,{useState}来自“React”;
从“react native”导入{文本、视图、图像、TouchableOpacity、样式表};
常量后内容=()=>{
常量后描述=
“Lorem Ipsum仅仅是印刷和排版行业的虚拟文本。自16世纪以来,Lorem Ipsum一直是该行业的标准虚拟文本,当时一家不知名的印刷商拿起一个打印工具,争先恐后地制作了一本字体样本书。它不仅存活了五个世纪,而且还跨越到了电子字体
 <Text
            numberOfLines={this.state.numberOfLines}
            onPress={() => this.handleSeeMore()}
            ellipsizeMode="middle"
            onTextLayout={({nativeEvent: {lines}}) =>
              this.setState({textLenth: lines.length === 3})
            }>
            This Gig Take a glance at the showcase of our artistic work:
            Modern and Trendy Logo Artworkslkjfkljf ksnfksfnsf Mascot &
            Custom Logo efdfg Artworks:lk knnk 'Explore the
            ultimate Experience..!' To fulfill your designing needs, Make us
            Graphically Yours...!! Why Team StrideInIt? We believe in our
            {'                      '}
            {this.state.textLenth && (
              <Text
                color="red"
                onPress={() => this.setState({numberOfLines: 0})}>
                see more
              </Text>
            )}
          </Text>
import React, {useState} from 'react';
import {Text, View, Image, TouchableOpacity, StyleSheet} from 'react-native';

const PostContent = () => {
  const postDescription =
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
  const [showMore, setShowMore] = useState(false);

  return (
    <View style={styles.postContentContainer}>
      {postDescription.length > 120 ? (
        showMore ? (
          <TouchableOpacity onPress={() => setShowMore(!showMore)}>
            <Text style={styles.postDescription}>{postDescription}</Text>
            <Text style={styles.seeMore}>Show less</Text>
          </TouchableOpacity>
        ) : (
          <TouchableOpacity onPress={() => setShowMore(!showMore)}>
            <Text style={styles.postDescription}>
              {`${postDescription.slice(0, 120)}... `}
            </Text>
            <Text style={styles.seeMore}>Show more</Text>
          </TouchableOpacity>
        )
      ) : (
        <Text style={styles.postDescription}>{postDescription}</Text>
      )}
    </View>
  );
};

export default PostContent;

const styles = StyleSheet.create({
  postContentContainer: {
    // borderWidth: 1,
    // borderColor: 'red',
    flexDirection: 'column',
  },

  postMedia: {
    //borderWidth: 1,
    //borderColor: 'red',
    width: '100%',
    height: 280,
    resizeMode: 'cover',
  },

  postDescription: {
    paddingTop: 15,
    paddingHorizontal: 15,
    color: colors.text.black,
    fontFamily: fonts.family.body,
    fontSize: fonts.fontSizes.button,
    fontWeight: fonts.fontWeights.thin,
  },

  seeMore: {
    paddingHorizontal: 15,
    color: colors.text.grey,
    fontStyle: 'italic',
    textDecorationLine: 'underline',
    fontFamily: fonts.family.body,
    fontSize: fonts.fontSizes.button,
    fontWeight: fonts.fontWeights.thin,
  },
});