css - 如何在 React 中隐藏包装组件

标签 css reactjs

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

<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,并将在第二行呈现。但是,我希望任何离开第一行的组件都不会被渲染。如何确保只有 component1 和 component2 显示并排除 component3?

最佳答案

您可以将所有组件的宽度累加到一个单独的变量中,并在已渲染组件的总宽度超过 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>

关于css - 如何在 React 中隐藏包装组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53021970/

相关文章:

reactjs - IndexRoute 未显示在路线内

html - 导航栏背景图片响应度,右侧有另一个容器

css - WP PageNavi 不接受 CSS 文件

jquery - 如何使用 jquery 切换 svg 的动画?

html - Z 索引在 IE 中不起作用

javascript - 在第二次请求后,react-http-request 不会更改加载状态

reactjs - 如何制作一个可滚动组件,当我附加子组件时自动滚动到最新的子组件?

javascript - 首先 react 代码

javascript - 在文本框中给定的新输入未在进度条中更新

javascript - 如何在 Radium 中包装 react redux connect?