Как свернуть часть текста внутри карточки в реакции bootstrap? - PullRequest
1 голос
/ 22 апреля 2020

У меня есть такая карта:

enter image description here

<Card className="m-5 border-0 shadow" style={styles.card}>
  <Row>
    <Col>
      <Card.Img src={require("../assets/images/findingsPage/EnglishesOfTheWorld.jpg")} style={styles.cardImage} />
    </Col>
    <Col>
      <Card.Body>
      <Card.Title as="h1">Englishes of the World</Card.Title>
      <Card.Text as="h4" style={styles.cardText}>
        How do your grammar intuitions depend on when and where you learned English? Participants took a short grammar quiz, which we are using to understand how grammar differs in different parts of the English-speaking world (USA, Ireland, Australia, etc.). We are also investigating how grammar is different for people who learn English later in life: Do they make different mistakes if their first language is German as opposed to Japanese?
      </Card.Text>
      </Card.Body>
    </Col>
  </Row>
</Card>

Можно ли свернуть часть текста, если длина текста выходит за пределы высоты карты следующим образом: https://mdbootstrap.com/plugins/jquery/extended-cards/

enter image description here

enter image description here

Спасибо.

1 Ответ

1 голос
/ 22 апреля 2020

Давайте начнем с демонстрации: https://codesandbox.io/s/cool-wright-u5old?file= / src / App. js

Лог c таков:

  • Вкл. смонтированный компонент, используйте ref, чтобы определить, превышает ли высота родительского текста ваш предел
  • Если это так, установите max-height (доберетесь до него) в качестве предела и покажите кнопку переключения
  • Когда пользователь нажимает на эту кнопку, он переключает max-height между пределом и максимально возможной высотой карты.

Причина использования max-height заключается в переходе. Это единственный способ сделать css только переход высоты.

Для удобства я извлек эту логику c в новый Компонент, но это можно сделать внутри оригинала компонент.

А теперь, к коду:

const MAX_POSSIBLE_HEIGHT = 500;

const ExpendableText = ({ maxHeight, children }) => {
  const ref = useRef();
  const [shouldShowExpand, setShouldShowExpand] = useState(false);
  const [expanded, setExpanded] = useState(true);

  useEffect(() => {
    if (ref.current.scrollHeight > maxHeight) {
      setShouldShowExpand(true);
      setExpanded(false);
    }
  }, [maxHeight]);

  return (
    <Card.Text as="h4" style={styles.cardText} ref={ref}>
      <div
        class="inner"
        style={{ maxHeight: expanded ? MAX_POSSIBLE_HEIGHT : maxHeight }}
      >
        {children}
      </div>
      {shouldShowExpand && (
        <button onClick={() => setExpanded(!expanded)}>Expand</button>
      )}
    </Card.Text>
  );
};

И css часть

.inner {
  overflow: hidden;
  transition: max-height 0.2s ease;
}

Наконец, компонент может потребляться следующим образом:

<ExpendableText maxHeight={95}>
  How do your grammar intuitions depend on when and where you
  learned English? Participants took a short grammar quiz, which
  we are using to understand how grammar differs in different
  parts of the English-speaking world (USA, Ireland, Australia,
  etc.). We are also investigating how grammar is different for
  people who learn English later in life: Do they make different
  mistakes if their first language is German as opposed to
  Japanese?
</ExpendableText>
  • Я включил изменение высоты в решение (потому что оно мне нравится). Если вам не нужен переход, решение будет немного короче.
  • Если вычислять высоту не нужно, потому что содержимое всегда будет сокращаться, решение будет проще.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...