使用行数的React native text组件

p3rjfoxz  于 2023-11-21  发布在  React
关注(0)|答案(4)|浏览(223)

有没有办法确定文本在使用行数时会被截断?已经到处找了,没有明确的答案。谢谢!

s2j5cfk0

s2j5cfk01#

您可以使用numberOfLines作为<Text />组件的props。它取决于您的组件的宽度,然后计算文本的长度。此prop通常与ellipsizeMode一起使用。示例:

  1. <Text numberOfLines={2} ellipsizeMode='tail'>
  2. Lorem Ipsum is simply dummy text of the printing and typesetting industry.
  3. </Text>

字符串

nle07wnf

nle07wnf2#

现在可以使用onTextLayout事件,其中包含一个正在渲染的lines数组。只需查看长度即可确定是否达到极限。lines数组中还有其他细节,如每行的实际高度和宽度,可以进一步用于确定文本是否被截断。

  1. const NUM_OF_LINES = 5;
  2. const SOME_LONG_TEXT_BLOCK = 'Fill in some long text yourself ...';
  3. return (<Text
  4. numberOfLines={NUM_OF_LINES}
  5. onTextLayout={({ nativeEvent: { lines } }) =>
  6. setState({ showMoreButton: lines.length === NUM_OF_LINES })
  7. }
  8. >
  9. {SOME_LONG_TEXT_BLOCK}
  10. </Text>;

字符串

gopyfrb3

gopyfrb33#

这对我来说很有效:)

  1. import React, { useState } from 'react'
  2. import { Text } from 'react-native'
  3. export function MoreLessText({ children, numberOfLines }) {
  4. const [isTruncatedText, setIsTruncatedText] = useState(false)
  5. const [showMore, setShowMore] = useState(true)
  6. return isTruncatedText ? (
  7. <>
  8. <Text numberOfLines={showMore ? numberOfLines : 0}>{children}</Text>
  9. <Text onPress={() => setShowMore(!showMore)}>
  10. {showMore ? 'Read More' : 'Less'}
  11. </Text>
  12. </>
  13. ) : (
  14. <Text
  15. onTextLayout={(event) => {
  16. const { lines } = event.nativeEvent
  17. setIsTruncatedText(lines?.length > numberOfLines)
  18. }}
  19. >
  20. {children}
  21. </Text>
  22. )
  23. }

字符串

展开查看全部
dffbzjpn

dffbzjpn4#

为了创建一个Instagram风格的评论,我这样做了(注意,我使用tailwind进行样式化,因为这是一个react原生应用程序,库是nativewind,我还使用了一个嵌套的文本,它允许我做一个web html <span>元素):

  1. const [more, setMore] = useState(false)
  2. const toggleShowMore = () => {
  3. setMore(!more)
  4. }
  5. <View className=" pl-1 pt-1 flex-row flex-1 max-w-[82%]">
  6. <Text numberOfLines={!more ? 3 : undefined}>
  7. <Text onPress={() => navigateUser(comment.user.username)} className="font-bold">
  8. @{comment.user?.username}{' '}
  9. </Text>{' '}
  10. <Text onPress={toggleShowMore}>{comment.content}</Text>
  11. </Text>
  12. </View>

字符串

相关问题