Sometimes for responsive layout, we need to adapt the height according to the width of the component. CSS cannot achieve this kind of dynamic change. Traditionally, jQuery is used to achieve this. This article mainly introduces the example code of React adapting height according to width. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
There is no need to rely on JQuery in React, the implementation is relatively simple, just change the width after DidMount.
Try on Codepen
It should be noted that changes must be synchronized during resize, and a listener needs to be registered
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 ( <p className="test" style={ { width: this.state.width, height: this.state.height } }> {`${this.state.width} x ${this.state.height}`} </p> ); } } ReactDOM.render( <Card/>, document.getElementById('root') );
Reference materials
##React life cycleJavaScript handles Iframe adaptive height (under the same or different domain names)
Solution to adaptive height in DIV+CSS layout
Mobile How to center text under adaptive height
The above is the detailed content of React adaptive height based on width example sharing. For more information, please follow other related articles on the PHP Chinese website!