截断文本-React Native

问题描述 投票:0回答:1

我有一个带有FlatList的React Native应用程序。

我添加的逻辑是,当第100位的角色不为空时,应添加扩展/折叠箭头,如下所示。短消息没有箭头图标。

enter image description here

enter image description here

嗯,这是不好的逻辑!!现在,当我将应用程序字体更改为大/小时,此逻辑将不起作用。它也不适用于汉字大声笑。因此,它不应该基于字符数。

{  alert.charAt(100) !== "" ?
                arrowClicked === true ? 
                <Icon type='materialicons' name='arrow-drop-up' onPress={()=>{this.setFullLength()}}  />
                : 
                <Icon type='materialicons' name='arrow-drop-down' onPress={()=>{this.setFullLength()}}  />
                : null
            } 

它应该检测到文本很长并且被截断。我该如何实现呢?请帮助!!!

javascript css reactjs react-native truncate
1个回答
0
投票

您应该使用onTextLayout并使用类似下面的方法确定行长。

function CustomText(props) {
  const [showMore, setShowMore] = React.useState(false);
  const [lines, setLines] = React.useState(props.numberOfLines);

  const onTextLayout = (e) => {
    setShowMore(
      e.nativeEvent.lines.length > props.numberOfLines && lines !== 0
    );
  };

  return (
    <View>
      <Text numberOfLines={lines} onTextLayout={onTextLayout}>
        {props.children}
      </Text>
      {showMore && (
        <Button title="Show More"
          onPress={() => {
            setLines(0);
            setShowMore(false);
          }}
        />
      )}
      {!showMore && (
        <Button title="Hide More"
          onPress={() => {
            setLines(props.numberOfLines);
          }}
        />
      )}
    </View>
  );
}

用法

  const text =
    'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to mak';

 <CustomText numberOfLines={2}>{text}</CustomText>

您也可以传递样式等其他道具。

© www.soinside.com 2019 - 2024. All rights reserved.