React根據寬度自適應高度

jxy發表於2017-10-10
  • 有時對於響應式佈局,我們需要根據元件的寬度自適應高度。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生命週期

相關文章