0

Установил свойство css, чтобы блок растягивался на всю оставшуюся высоту экрана

flex-grow: 1

Теперь не могу понять, как динамически считать высоту при изменении размеров окна. Пока только высота устанавливается после рендера компонента в componentDidMount

Демо https://codesandbox.io/s/dynamic-calc-height-4t1zv?file=/src/Tile.js:163-180

Пример кода

class Help extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      elementHeight: 0
    };
  }

  componentDidMount() {
    this.setState({ elementHeight: this.divRef.clientHeight });
  }

  render() {
    return (
      <div className="tile" ref={(element) => (this.divRef = element)}>
        Div height: {this.state.elementHeight + " px"}
      </div>
    );
  }
}

1 ответ 1

1
import React from "react";

class Help extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      elementHeight: 0
    };
    this.divRef = React.createRef();
  }

  resizeHandler = ()=>{
    this.setState({ elementHeight: this.divRef.current.clientHeight });
  }

  componentDidMount() {
    this.resizeHandler();
    window.addEventListener('resize',this.resizeHandler);
  }

  componentWillUnmount(){
    window.removeEventListener('resize',this.resizeHandler);
  }

  render() {
    return (
      <div className="tile" ref={this.divRef}>
        Div height: {this.state.elementHeight + " px"}
      </div>
    );
  }
}

export default Help;

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.