簡體   English   中英

使用行數反應原生文本組件

[英]React native text component using number of lines

有沒有辦法確定使用行數時文本何時被截斷? 一直在到處尋找,沒有明確的答案。 謝謝!

您可以使用numberOfLines作為<Text />組件的道具。 它取決於組件的寬度,然后計算文本的長度。 此道具通常與ellipsizeMode一起ellipsizeMode 例子:

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

現在可以通過onTextLayout事件實現這一點,該事件包括渲染出的lines數組。 只需查看長度即可確定是否達到極限。 lines數組中還有其他詳細信息,例如每行的實際高度和寬度,可進一步用於確定文本是否被截斷。

const NUM_OF_LINES = 5;
const SOME_LONG_TEXT_BLOCK = 'Fill in some long text yourself ...';

return (<Text
  numberOfLines={NUM_OF_LINES}
  onTextLayout={({ nativeEvent: { lines } }) =>
    setState({ showMoreButton: lines.length === NUM_OF_LINES })
  }
>
  {SOME_LONG_TEXT_BLOCK}
</Text>;

這對我有用:)

import React, { useState } from 'react'

import { Text } from 'rect-native'

export function MoreLessText({ children, numberOfLines }) {
  const [isTruncatedText, setIsTruncatedText] = useState(false)
  const [showMore, setShowMore] = useState(true)

  return isTruncatedText ? (
    <>
      <Text numberOfLines={showMore ? numberOfLines : 0}>{children}</Text>
      <Text onPress={() => setShowMore(!showMore)}">
        {showMore ? 'Read More' : 'Less'}
      </Text>
    </>
  ) : (
    <Text
      onTextLayout={(event) => {
        const { lines } = event.nativeEvent
        setIsTruncatedText(lines?.length > numberOfLines)
      }}
    >
      {children}
    </Text>
  )
}

為了創建一個帶有閱讀更多內容的instagram樣式評論,我這樣做了(請注意,我使用tailwind進行樣式設置,因為這是一個react-native應用程序,lib是nativewind ,我還使用了一個允許我做的嵌套文本web html <span>元素):

const [more, setMore] = useState(false)

const toggleShowMore = () => {
 setMore(!more)
}
<View className=" pl-1 pt-1 flex-row flex-1 max-w-[82%]">
    <Text numberOfLines={!more ? 3 : undefined}>
         <Text onPress={() => navigateUser(comment.user.username)} className="font-bold">
                @{comment.user?.username}{' '}
         </Text>{' '}
         <Text onPress={toggleShowMore}>{comment.content}</Text>
     </Text>
 </View>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM