首页 > 解决方案 > 如何根据父 div 的高度调整 ReactJS 组件的高度?

问题描述

我有一个 React 组件(代码中的 Cartouche),我在一个 div 中调用了 x 次,具体取决于我在哪个 div 中调用它。例如,我有一个高度为:690px 的 div 和另一个高度为:450px 的 div,我在每个 div 中调用相同的组件 x 次,具体取决于 div。我希望组件调整大小,使其完全适合每个 div。

已经尝试使用 % 更改 CSS 中的组件大小,但它不起作用。

//Component

export default function Cartouche(props) {

    return (
        <div style={{ width: '100%', backgroundColor: '#E5E2E2', marginTop: '2%', marginBottom: '5%', borderRadius: 30, height: 'auto' }}>
            <div style={{ fontWeight: 'bold' }}>{props.data.STRING_1}</div><br />
            <div style={{ textTransform: 'uppercase' }}>{props.data.STRING_2}</div>
            <div style={{ border: 'solid 1px black', width: '25%', position: 'absolute', zIndex: '-1', height: 20, marginLeft: '2%', borderRadius: '0 0 10px 10px' }}>
                <div style={{ position: "absolute", bottom: 3, left: 5 }}>
                    {props.data.TIME}
                </div>
            </div>
        </div >
    )


//First div in which I call it 5 times

 return (
        < div >

            <div style={{ width: document.body.scrollWidth / 2.165, backgroundColor: 'white', height: 690, margin: '1% 0', padding: 25, borderRadius: 25, position: 'absolute', left: 11, zIndex: -1 }}>
                <div id='parent' style={{ display: 'flex', alignItems: 'center', width: '100%', justifyContent: 'center' }}>
                    <div style={{ textAlign: 'center', border: '2px solid black', borderRadius: '50px', padding: '0 5%', display: 'flex' }}>
                        <h3 style={{ margin: 0 }}>PLAYLIST</h3>
                    </div>
                </div>
                <div id="cartouchePlaylist" style={{}}>
                    {Playlist ? displayPlaylist() : null}
                </div>

            </div>



        </div>
    );


//Second div in which I call it 6 times

        < div >
            <div style={{ width: document.body.scrollWidth / 2.165, backgroundColor: 'white', height: 360, marginTop: '17.6%', marginLeft: '-48.2%', padding: 25, borderRadius: 25, position: 'absolute', right: 18, top: -118 }}>
                <div id='parent' style={{ display: 'flex', alignItems: 'center', width: '100%', justifyContent: 'center' }}>
                    <div style={{ textAlign: 'center', border: '2px solid black', borderRadius: '50px', padding: '0 5%', display: 'flex' }}>
                        <h3 style={{ margin: 0 }}>CARTOUCHIER</h3>
                    </div>
                </div>
                <div style={{}}>
                    {Cartouchier ? displayCartouchier() : null}
                </div>
            </div>
        </div>
    );

标签: javascripthtmlcssreactjs

解决方案


使用 minHeight 而不是 height,因此如果高度超过它会相应地调整大小,但绝不会小于我们指定的 minHeight。


推荐阅读