简体   繁体   中英

show more and show less dinamicaly for each div

when I click the particular show more button the content should be displayed, the condition is the whole component should not re-rendering
I have used a useState when I clicked the button it is re-rendering the whole component it is taking a long time to re-render every div give an easy solution for this.

const [arr,setmarr] =useState([])
const oncl=(e)=>{
setarr((prev)=>[...prev,e.target.value])
}
return{
divarray.map((i,j)=>{
        {console.log("tdic)")}
        return(
          <Commentbox divarr={arr[j]} value={j} oncl={(e)=>oncl(e) } />
        )
        }
      }

Commentbox component

return 
<div>
  div{j}

// some icons here

{divarr && <div> right side div </div>}
<button onClick={(e)=>{oncl(e)}}  value={j} >see more</button >
</div>

before onClick on showmore

在此处输入图像描述

after showmore button has been clicked on the second div在此处输入图像描述

you should change each box to a component to solve this problem. make that component with class base component because you need getSanpShotBeforeUpadte .

getSanpShotBeforeUpadte : you can control your component's render with this method.dont forget this method will give you nextProps,nextState and snapshot as parameter

class Box extends Component{
  state = {
    // more
    showMore: false,
  }

  getSnapshotBeforeUpdate(nextProps,nextState){
    // OTHER CONDITIONS
    
    if(nextState.showMore !== this.state.showMore) return true
    return false
  }

  render(){
    return (
      <div>
        {/* CODE ... */}
        <div style={{display: this.state.showMore ? 'block' : 'none'}}>
          HERE IS A TEXT 
        </div>
        <button onClick={()=>this.setState({showMore: !this.state.showMore})}>show more</button>
      </div>
    )
  }
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM