截断文本 - React Native

gro*_*oot 1 javascript css truncate reactjs react-native

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

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

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

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

Run Code Online (Sandbox Code Playgroud)

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

Gur*_*ran 6

您应该使用 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>
  );
}
Run Code Online (Sandbox Code Playgroud)

用法

  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>
Run Code Online (Sandbox Code Playgroud)

您也可以传递其他道具,例如样式。

  • 请注意,在这里说“谢谢”的首选方式是对好的问题和有帮助的答案进行投票,并[接受](https://stackoverflow.com/help/someone-answers)对任何问题最有帮助的答案你问的问题 (2认同)