简体   繁体   中英

offsetHeight returns 0 when rendering text into a div using a API

I have a div which renders some text taken from a API call. I want to add a See more button if it exceeds 3 lines. Following is my implementation for that.

         seeMore(){
            this.setState({
            seeMore: !this.state.seeMore
          })
         }

Inside render method

        function countLines() {
            var el = document.getElementById("about");
            var divHeight = el && el.offsetHeight;
            var lines = divHeight / 24;
            return lines;
        }

//above 24 is my line height.

Inside return

 <div>
       <div id="about" style={{WebkitLineClamp:seeMore ? '':3}}>
          {expert.bio}
       </div>
       {expert.bio !== undefined && (countLines() >= 3 && 
       <span onClick={this.seeMore.bind(this)}>{seeMore === true ? 'See less': 'See more'}</span>)}
 </div>

In the above solution my offsetHeight always returns a 0 even though there are content inside the div. I have set a condition to run the countLines function only when content is available. But still i get a 0 value for offsetHeight .

I have tried this solution with hardcoded values and then this works. It doesn't work only when rendering the text that is taken from a API.

function countLines() {
        var el = document.getElementById("about").clientHeight;
        var lines = el / 24;
        return lines;
    }

You have tried this It will be worked.

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