我正在尝试渲染一个组件,其样式和位置是根据某些情况确定的。为了做到这一点,我将它渲染在一个占据整个主体的容器中,并且组件在其中移动。而不是那样做,如何确保容器的样式与组件的样式相同?我不希望容器占据整个 body ,我只希望它占据组件。
代码:
var componentStyle;
//cases
componentStyle = {}; //some css properties
var MyComponent = React.createClass({
render: function(){
return(
<div style = {componentStyle}>Some content</div>
)
}
})
var container = document.createElement("div");
container.id = "container";
document.body.appendChild(container);
ReactDOM.render(<MyComponent/>,container);
容器的CSS:
#container {
position: absolute;
top:0;left: 0;
font-family: Arial, Helvetica, sans;
background: transparent;
height: 100%;
width: 100%;
z-index:9999999;
}
最佳答案
这更像是 CSS 问题而不是 React 问题。
如果您不希望容器占据整个主体,您应该在 CSS 中删除 width: 100%
。 (我假设您的 DOM 结构类似于:
<body>
<div id="container">
<Children />
</div>
</body>
如果你想让它占据组件,css应该是
#container {
display: table;
}
或
(默认会添加额外边距)
#container {
display: inline-block;
}
或
仅在 CSS3 中
#container {
width: fit-content;
/* To adjust the height as well */
height: fit-content;
}
或
也仅限 CSS3。
#container {
width: intrinsic;
}
查看更多详情 here
关于css - 调整容器 div 的大小以完全适合呈现的 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39163445/