Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

javascript - Check how many lines of text in p and store in variable

I have a table with a column called "comments". In a particular cell, ONLY when there are more than 2 lines of text I want to:

  • render a clickable text showing "show more"
  • line clamp the text to 2 lines

Currently, I have a line clamp in every cell set like so:

const ClampedText = styled.p`
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
`;

This element is used like so: <ClampedText>{description}</ClampedText> where description is the text in a cell.

Using styled-components.

What I basically want to do is get a boolean variable stating wether there are more than two lines of text in a particular p- and then conditionally render the component accordingly (with/without "show more" and line-clamp.)

How can this be done?

Idea

The "comments" column has 10% of the width of the table, so I'm thinking that can be used somehow with som JS and calculating the number of lines going to be showing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use string.length to know the length and decide to show a show more link or not. Here is the full code on codesandbox

  const [paragraph, setParagraph] = useState({
    show: null,
    paragraph: "",
    clicked: false
  });

   ...

  return (
    <>
      <p>
        {paragraph.paragraph}
        <span
          style={{ display: paragraph.show ? "inline" : "none" }}
          onClick={() =>
            setParagraph({
              show: true,
              clicked: !paragraph.clicked,
              paragraph: paragraph.clicked
                ? dummyText.substring(0, 25).concat(" ... ")
                : dummyText
            })
          }
        >
          {paragraph.clicked ? "Show less" : "Show more"}
        </span>
      </p>
    </>
  );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...