2016-11-07 97 views
0

我的成分是什麼廣告如下:高度自動帶絕對位置

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

撥弄不工作 –

+0

不工作,因爲'高度:200像素;'在CSS被註釋掉。我想解決它沒有特定的寬度。 – Boky

+0

你應該創建一個最小的例子,沒有javascript – giorgio

回答

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> 
    ) 
    } 
} 

jsfiddle

+0

唯一的問題是,子元素在父組件中。我的代碼有點不同。 [的jsfiddle](https://jsfiddle.net/69z2wepo/61848/) – Boky