LoginSignup
5
2

More than 3 years have passed since last update.

ReactNativeで「続きを読む/続きを見る」を実装する

Last updated at Posted at 2021-04-13

省略したTextコンポーネントを展開するUIを実装する方法

React Nativeで、インスタやTwitterなどの省略した文章を展開する「続きを見る」ボタンを実装する方法がなかなか見つからなかったので作ってみた。
展開した状態で行数を取得し、その後すぐに縮小している。省略・展開にはnumberOfLinesを利用している。
以下は行数が2行より多い場合に、続きを見るボタンを表示するサンプルである。

投稿のキャプション部分を実装した例
const Caption = ({navigation, text}) => {
  const onTextLayout = ({nativeEvent: {lines}}) => {
    // 展開された状態の行数を取得する
    if (typeof lineCount === "undefined"){
      setLineCount(lines.length)
      setIsExpanded(false)
    }
  }
  const [lineCount, setLineCount] = useState() // はじめはundefinedにしておく
  const [isExpanded, setIsExpanded] = useState(true)

  return (
    <Text numberOfLines={isExpanded ? undefined : 2} onTextLayout={onTextLayout}>{text}</Text>
    // 行数が2行より多く、省略されている場合のみ「続きを見る」ボタンを追加
    {lineCount > 2 && !isExpanded && <Text onPress={() => setIsExpanded(true)}>続きを見る</Text>}
  )
}

より良い方法があれば、ぜひ教えて下さい!!

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2