我的组件是广告如下:
class Test extends React.Component {
outterDivStyles() {
return {
position: "relative",
width: "100%",
overflow: "hidden",
/*height: this.props.height || 200*/
}
}
innerDivStyles(){
return {
position: "absolute",
top: 0,
left: 0,
right: 0,
width: "1000%",
transition: "left .5s",
transitionTimingFunction: "ease"
}
}
render(){
return(
<div>
<div ref="detailsOutterDiv" className="detailsOutterDiv" style={this.outterDivStyles()}>
<div ref="detailsInnerDiv" className="detailsInnerDiv" style={this.innerDivStyles()}>
<div className="slide" ><img src="http://placehold.it/250x200" /></div>
</div>
</div>
</div>
)
}
React.render(<Test />, document.getElementById('container'));
而css是:
.detailsOutterDiv{
background-color: #f00;
/*height: 200px;*/ //if the height is 200px, then it's ok, but can it be done without that?
width: 300px;
display: block;
}
.slide img{
display: block;
height: auto;
}
如果父div没有特定的高度,图像是否有任何显示全高的方式?
这是jsfiddle。
答案 0 :(得分:1)
图像加载后,您必须获得detailsInnerDiv
的高度。
为了做到这一点,您必须使用offsetHeight
来获取高度,将其存储在组件state
中并将其分配给detailsOutterDiv
。
像这样的东西
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
height: 0
};
}
get outterDivStyles() {
return {
position: "relative",
width: "100%",
overflow: "hidden",
/*height: this.props.height || 200*/
}
}
get innerDivStyles(){
return {
position: "absolute",
top: 0,
left: 0,
right: 0,
width: "1000%",
transition: "left .5s",
transitionTimingFunction: "ease"
}
}
render(){
return(
<div>
<div
ref="detailsOutterDiv"
className="detailsOutterDiv"
style={{...this.outterDivStyles,height : this.state.height }}
>
<div
ref={node => this.detailsInnerDiv = node}
className="detailsInnerDiv"
style={this.innerDivStyles}
>
<div className="slide" >
<img
onLoad={() => this.setState({height:this.detailsInnerDiv.offsetHeight})}
src="http://placehold.it/250x200"
/>
</div>
</div>
</div>
</div>
)
}
}