React 钩子在 youtube 评论部分显示 more/less 文本

React hooks show more/less text like in youtube comments section

我在 youtube 评论部分有一些评论,我不想让它显示 less/more 长评论按钮。我坚持了一种在没有完全重新渲染(块的重建)或任何状态值的情况下在项目上本地执行此操作的方法。

function commentsGenerate() {
    let block = comments.map((comment, i) => {
        let splitLength = 400
        let shortDesc = comment || '' // for null vals

        let shortened = false
        if (shortDesc.length > splitLength) shortened = true

        shortDesc = shortDesc.substring(0, splitLength)

        return (
          <div key={i}>
            <div>{`${shortDesc}${shortened ? '...' : ''}`}</div>
            {shortened && <Button onCLick={ () => {'how?'} >More</Button>}
          </div >
        )
      })


    setSectionBlock(block)
  }

如果不在某处使用状态,您就不能做这种事情。t/shouldn。在这种情况下,我建议您将注释代码和状态分离到一个单独的组件中,该组件可以处理自己的展开状态。然后您可以使用状态来调整输出的渲染和样式:

import React, { useState } from 'react'

// ... //

const Comment = ({comment:shortDesc = ''})=>{
    let splitLength = 400
    let shortened = false
    const [isExpanded, setIsExpanded] = useState(false)
    if (shortDesc.length > splitLength) shortened = true

    shortDesc = shortDesc.substring(0, splitLength)
    const handleToggle = ()=>{
        setIsExpanded(!isExpanded)
    }
    return (
      <div key={i}>
        {!isExpanded ? <div>{`${shortDesc}${shortened ? '...' : ''}`}</div> : null}
        {shortened && <Button onClick={handleToggle}>{isExpanded?'Less':'More'}</Button>}
      </div >
    )
  }

像这样在您的映射中使用此组件:

 let block = comments.map((comment, i) => <Comment comment={comment} key={i} /> )