【问题标题】:Truncate Text - React Native截断文本 - React Native
【发布时间】:2020-09-30 15:02:15
【问题描述】:

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

我添加的逻辑是,只要第 100 位的字符不为空,就应该添加展开/折叠箭头,如下所示。短消息没有箭头图标。

嗯,这是一个糟糕的逻辑!现在,当我将应用程序字体更改为大/小时,此逻辑将不起作用。它也不适用于汉字 LOL。所以它不应该基于字符数。

{  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
            } 

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

【问题讨论】:

  • 也许这可以帮助你:css-tricks.com/line-clampin
  • 没有。对于“字体:正常”,我可以做到这一点。现在我将字体更改为“大”,那么这将无法正常工作?

标签: javascript css reactjs react-native truncate


【解决方案1】:

您应该使用 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>

您也可以传递样式等其他属性。

【讨论】:

  • 这太棒了!!!但这将为每一行显示“显示更多”和“隐藏更多”。它应该只显示长消息而不是短消息。我该如何限制它??
  • 你改变了 numberOfLines 吗?
  • 行数={3}。假设我有 2 条消息。一条消息只有 1 行。第二条消息很长,像 10 行。 “显示更多”功能应仅显示长消息。 (这是我公司的要求,不是我的哈哈)
  • 啊,你可以把逻辑放在显示按钮上
  • 请注意,在这里说“谢谢”的首选方式是对好的问题和有用的答案进行投票,accepting 是对您提出的任何问题的最有用的答案
猜你喜欢
  • 1970-01-01
  • 2023-01-19
  • 2021-01-23
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多