【问题标题】:React JS element width same as its heightReact JS元素宽度与其高度相同
【发布时间】:2021-01-25 20:55:12
【问题描述】:

我是 React JS 的新手。现在正在努力解决我需要将元素宽度设置为等于其高度的小事。我们可以在 jQuery 中进行如下管理:

var divWidth = $('.main').width(); 
$('.main').height(divWidth);

$( window ).resize(function() {
var divWidth = $('.main').width(); 
$('.main').height(divWidth);
});
.container {
  width: 100%;
  max-width: 400px;
}

.main {
  width: 100%;
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="container">
  <diV class="main">
    test
  </diV>
</div>

我们如何在 React JS 中做到这一点?

【问题讨论】:

    标签: html jquery css reactjs


    【解决方案1】:

    您可以使用 jquery 窗口侦听器将道具传递给组件并设置其样式。它会产生同样的效果。

    import React, { Fragment, useState, useEffect } from "react";
    import ReactDOM from "react-dom";
    
    function LiveVisitors() {
      const [dimensions, setDimensions] = useState({
        x: document.body.clientWidth,
        y: document.body.clientHeight
      });
    
      window.addEventListener("resize", () => {
        setDimensions({
          x: document.body.clientWidth,
          y: document.body.clientHeight
        });
      });
    
      let fraction = dimensions.x / 10;
    
      return (
        <div
          style={{
        border: "1px solid red",
        width: fraction,
        height: fraction
          }}
        >
          {JSON.stringify(dimensions)}
        </div>
      );
    }
    
    const wrapper = document.getElementById("container");
    ReactDOM.render(<LiveVisitors />, wrapper);
    

    你可以修改这个游乐场:https://codesandbox.io/s/react-playground-forked-v66j1?file=/index.js:0-719

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 2018-12-29
      • 1970-01-01
      • 2015-07-13
      • 1970-01-01
      相关资源
      最近更新 更多