首页 > 解决方案 > react-native 自定义文本省略号以在省略号后添加“更多”

问题描述

以下来自以使用 react-native 而闻名的 instagram

如您所见,More省略号 (...) 后面有一个文本 (더보기,意思是 )
我怎样才能模拟呢?

在此处输入图像描述

标签: react-native

解决方案


这是一个快速的解决方法。创建一个将文本作为参数的函数,并使用更多按钮显示截断的文本。单击后,我们将使用较少的按钮呈现全文。

const MoreLessComponent = ({ truncatedText, fullText }) => {
  const [more, setMore] = React.useState(false);
  return (
    <Text>
      {!more ? `${truncatedText}...` : fullText}
      <TouchableOpacity onPress={() => setMore(!more)}>
        <Text>{more ? 'less' : 'more'}</Text>
      </TouchableOpacity>
    </Text>
  );
};

const MoreInfo = (text, linesToTruncate) => {
  const [clippedText, setClippedText] = React.useState(false);
  return clippedText ? (
    <MoreLessComponent truncatedText={clippedText} fullText={text} />
  ) : (
    <Text
      numberOfLines={linesToTruncate}
      ellipsizeMode={'tail'}
      onTextLayout={(event) => {
        //get all lines
        const { lines } = event.nativeEvent;
        //get lines after it truncate
        let text = lines
          .splice(0, linesToTruncate)
          .map((line) => line.text)
          .join('');
        //substring with some random digit, this might need more work here based on the font size
        //
        setClippedText(text.substr(0, text.length - 9));
      }}>
      {text}
    </Text>
  );
};


现在这样称呼

<View>
        {MoreInfo('Change code in the editor and watch it change on your phone! Save to get a shareable url.')}
      </View>

这是小吃https://snack.expo.io/@saachitech/react-native-more-less


推荐阅读