有時對于響應(yīng)式布局,我們需要根據(jù)組件的寬度自適應(yīng)高度。CSS無法實現(xiàn)這種動態(tài)變化,傳統(tǒng)是用jQuery實現(xiàn)。
而在React中無需依賴于JQuery,實現(xiàn)相對比較簡單,只要在DidMount后更改width即可
需要注意的是在resize時候也要同步變更,需要注冊個監(jiān)聽器
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就自適應(yīng) 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生命周期
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答