有時對于響應式布局,我們需要根據組件的寬度自適應高度。CSS無法實現這種動態變化,傳統是用jQuery實現。
而在React中無需依賴于JQuery,實現相對比較簡單,只要在DidMount后更改width即可
需要注意的是在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()); } componentWillUnmount() { window.removeEventListener('resize', () => this.updateSize()); } 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生命周期
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答