Home > Web Front-end > JS Tutorial > body text

React adaptive height based on width example sharing

小云云
Release: 2018-01-25 11:40:49
Original
2631 people have browsed it

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(&#39;root&#39;)
);
Copy after login

Reference materials

##React life cycle


Related recommendations:


JavaScript 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template