【问题标题】:Cannot set height with percentages in React无法在 React 中使用百分比设置高度
【发布时间】:2021-06-27 14:10:03
【问题描述】:

我想在 react 中构建一个闹钟应用程序,但我遇到了一个奇怪的问题。 我有一个包含所有警报组件的容器,我无法以百分比为它们设置高度。 有没有办法以百分比传递高度,而不是 px/vh?

容器

function Container() {
return (
    <div className="container">
        <Alarm />
        <Alarm />
        <Alarm />
    </div>
)

}

容器样式

.container{
  position: absolute;
  top: 7%;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  min-height: 60vh;
  display: flex;
  flex-direction: column;
}

Alarm.js

function Alarm() {

    return (
        <div className="alarm">
            quack quack
        </div>
    )
}

闹钟样式

.alarm{
  width: 100%;
  height: 20%;

  &:not(:first-child){
    margin-top: 50px;
  }
}

【问题讨论】:

    标签: javascript css reactjs


    【解决方案1】:

    要使百分比高度起作用,父母的高度应该是可确定的,但在您的情况下,.container 的高度取决于它的孩子。 要使.alarm 组件的百分比高度起作用,请为.container 元素提供高度

    function Alarm() {
    
      return ( 
        <div className = "alarm" >
          quack quack
        </div>
      )
    }
    
    function Container() {
      return (
        <div className = "container" >
          <Alarm />
          <Alarm />
          <Alarm />
        </div>
      )
    }
    
    ReactDOM.render( <Container /> , document.querySelector('#root'))
    .app {
      height: 300px;
      width: 500px;
    }
    
    .container {
      position: absolute;
      top: 7%;
      left: 50%;
      transform: translateX(-50%);
      width: 90%;
      min-height: 60vh;
      display: flex;
      flex-direction: column;
      background-color: #ffff0088; /* only to visually distinguish */
      height: 300px; /* <-- Changed */
    }
    
    .alarm {
      width: 100%;
      height: 20%;
      background-color: #0000ff88; /* only to visually distinguish */
    }
    
    .alarm:not(:first-child) {
      margin-top: 50px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id='root' />

    【讨论】:

      【解决方案2】:

      我认为他们可能是一些原因造成的

      1. 父容器的样式(包含所有内容)
      • 你可以给它一个position of relative和一个高度在```px/vh`` 然后 100% 就可以了。

      【讨论】:

      • 它确实有效,当我将 min-height 更改为 height 时,我不必将位置更改为相对,并且可以在 vh 中传递高度,但仍然感谢您的回答!
      猜你喜欢
      • 1970-01-01
      • 2021-03-13
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      • 2013-08-20
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多