2017-09-04 77 views
0

我想從React中的子組件內的父組件調用方法。這是我的父組件的代碼:當子組件調用方法時,父引用爲null - ReactJS

import Video from 'Video/Video'; 

class CaseHeader extends React.Component { 

    constructor(props) { 
    super(props); 

    // Bind functions 
    this.videoComponentDidMount = this.videoComponentDidMount.bind(this); 
    } 

    videoComponentDidMount() { 
    console.log(this.caseheader); 
    } 

    render() { 
    let video = null; 

    if (this.props.caseData.title) { 
     video = <Video videoComponentDidMount={this.videoComponentDidMount} />; 
    } 

    return(
     <div styleName="CaseHeader" ref={caseheader => this.caseheader = caseheader}> 
     {video} 
     </div> 
    ); 
    } 

} 

export default CaseHeader; 

所以我想要做的是這樣的:我的CaseHeader組件被渲染所謂Video另一個組件。我需要等待這個組件完成渲染以獲得他的身高。所以我將一個方法傳遞給Video,這個方法將在componentDidMount方法中調用。當方法被調用時,我知道Video組件被渲染,我可以得到它的offsetHeight。這是Video組件的代碼:

class Video extends React.Component { 

    constructor(props) { 
    super(props); 
    } 

    componentDidMount() { 
    this.props.videoComponentDidMount(); 
    } 

    render() { 
    return(
     <div styleName="Video" ref={video => this.video = video}></div> 
    ); 
    } 

} 

export default Video; 

所以我希望console.log(this.caseheader)語句來記錄CaseHeader的DOM元素。問題是這不會發生,null取而代之。

當我添加以下代碼CaseHeader組分:

componentDidMount() { 
    console.log(this.caseheader); 
} 

componentDidMount方法記錄該權值,但videoComponentDidMount方法沒有。這是我正在談論的屏幕截圖:https://imgur.com/PrYRy0r

所以我的問題是:當從子組件調用函數時,如何定義父文件(在這種情況下爲this.caseheader)?

預先感謝您!

編輯

感謝幫助我在這裏使用CaseHeader的狀態,解決了這個問題。我所做的是更新的構造函數,並添加了一個方法:

constructor(props) { 
    super(props); 

    // Set initial state 
    this.state = { 
    videoIsActive: false 
    }; 

    // Bind functions 
    this.handleStateChange = this.handleStateChange.bind(this); 
} 

handleStateChange(state) { 
    this.setState(state); 
} 

所以我在這裏跟蹤關閉視頻是活動的。我還通過handleStateChange方法將Video部件:

video = <Video updateParentState={this.handleStateChange} />;

Video分量I加入下列:

this.props.updateParentState({videoIsActive: true});

這要求在CaseHeader以下代碼:

componentDidUpdate() { 
    if (this.state.videoIsActive) { 
    this.setCaseheaderBackgroundHeight(); 
    } 
} 

謝謝你們!

+0

難道是因爲ref回調被定義爲內聯函數,意思是先調用null?請參閱https://facebook.github.io/react/docs/refs-and-the-dom。html#注意事項 –

+0

我該如何設置另一種方式? – DavidWorldpeace

+0

爲什麼你不使用caseHeader中的setState設置視頻的offsetHeight?因此,Video類的componentDidMount將offsetHeight值傳遞給父Component,並在CaseHeader videoComponentDidMount中使用該值設置狀態。然後通過調用this.state.offsetHeight訪問offsetHeight屬性? – Trinu

回答

1

你爲什麼不在caseHeader中用setState設置視頻的offsetHeight?因此,Video類的componentDidMount將offsetHeight值傳遞給父Component,並在CaseHeader videoComponentDidMount中使用該值設置狀態。然後通過調用this.state.offsetHeight訪問offsetHeight屬性?