我需要能够隐藏被包裹的组件,因为它超过了最大宽度。
<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/