我想從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();
}
}
謝謝你們!
難道是因爲ref回調被定義爲內聯函數,意思是先調用null?請參閱https://facebook.github.io/react/docs/refs-and-the-dom。html#注意事項 –
我該如何設置另一種方式? – DavidWorldpeace
爲什麼你不使用caseHeader中的setState設置視頻的offsetHeight?因此,Video類的componentDidMount將offsetHeight值傳遞給父Component,並在CaseHeader videoComponentDidMount中使用該值設置狀態。然後通過調用this.state.offsetHeight訪問offsetHeight屬性? – Trinu