我有一些评论,例如youtube评论部分,我不想让它显示“长/短”按钮。我对在项目上进行局部处理而没有完全重新渲染(重新构建块)或任何状态值的做法有些坚持。
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)
}
答案 0 :(得分:2)
如果不在某处使用状态,则不能/不应该做这种事情。在这种情况下,我建议您将注释代码和状态分成一个单独的组件,该组件可以处理其自己的扩展状态。然后,您可以使用状态来调整输出的呈现和样式:
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} /> )