React根據寬度自適應高度

  • 有時對於響應式佈局,咱們須要根據組件的寬度自適應高度。CSS沒法實現這種動態變化,傳統是用jQuery實現。
  • 而在React中無需依賴於JQuery,實現相對比較簡單,只要在DidMount後更改width便可
  • Try on Codepen
  • 須要注意的是在resize時候也要同步變動,須要註冊個監聽器
class Card extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      width: props.width || -1,
      height: props.height || -1,
    }
  }

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

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

  updateSize() {
    try {
      const parentDom = ReactDOM.findDOMNode(this).parentNode;
      let { width, height } = this.props;
      //若是props沒有指定height和width就自適應
      if (!width) {
        width = parentDom.offsetWidth;
      }
      if (!height) {
        height = width * 0.38;
      }
      this.setState({ width, height });
    } catch (ignore) {
    }
  }

  render() {
    return (
      <div className="test" style={ { width: this.state.width, height: this.state.height } }> {`${this.state.width} x ${this.state.height}`} </div>
    );
  }
}

ReactDOM.render(
  <Card/>,
  document.getElementById('root')
);複製代碼

參考資料

  • React生命週期

React生命週期
React生命週期
相關文章
相關標籤/搜索