【问题标题】:How to hide wrapped components in React如何在 React 中隐藏包装的组件
【发布时间】:2019-03-31 23:54:15
【问题描述】:

我需要能够隐藏被包裹的组件,因为它超出了最大宽度。

<div style={{width:100}}>
    <div style={{width:50}}>
        component1
    </div>
    <div style={{width:50}}>
        component2
    </div>
    <div style={{width:50}}>
        component3
    </div>
</div>

//But I actually use map to render children
<div style={{width:100}}>
    {components.map((item, index) => {
        return <div style={{width:50}}>component{index + 1}</div>)
    }}
</div>

如上代码所示,父 div 为 100。所以最后一个组件(component3)将超出父组件 50px 的宽度,并在第二行渲染。但是,我希望任何离开第一行的组件根本不被渲染。如何确保只有组件 1 和组件 2 显示和排除组件 3?

【问题讨论】:

  • 如果所有组件的宽度都为 50,您可以使用 components.slice(0,2).map(...) 来渲染前两个组件。
  • @Tholle 是的,但不幸的是事实并非如此。宽度是可变的
  • 好的。父变量的宽度也是100吗?
  • @Tholle no 父 div 的宽度不可变

标签: css reactjs


【解决方案1】:

您可以在一个单独的变量中将所有组件的宽度相加,并在已渲染的总宽度超过 100 后为剩余的所有组件渲染 null

示例

class App extends React.Component {
  state = {
    components: [{ width: 50 }, { width: 50 }, { width: 50 }]
  };
  
  render() {
    const { components } = this.state;
    let totalWidth = 0;

    return (
      <div style={{ width: 100 }}>
        {components.map((item, index) => {
          totalWidth += item.width;

          if (totalWidth > 100) {
            return null;
          }
          return (
            <div key={index} style={{ width: 50 }}>
              component{index + 1}
            </div>
          );
        })}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2021-06-03
    • 2020-08-29
    相关资源
    最近更新 更多