我正在尝试从 React 中的子组件内部的父组件调用方法。这是我的父组件的代码:
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
方法没有。这是我正在谈论的内容的屏幕截图:/image/fr0ti.jpg
所以我的问题是:当从子组件调用函数时,如何定义父引用(在本例中为 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
组件我添加了以下内容:
this.props.updateParentState({videoIsActive: true});
这会调用 CaseHeader
中的以下代码:
componentDidUpdate() {
if (this.state.videoIsActive) {
this.setCaseheaderBackgroundHeight();
}
}
谢谢大家!
最佳答案
为什么不在 caseHeader 中使用 setState 设置视频的 offsetHeight?因此,在 Video 类的 componentDidMount 中将 offsetHeight 值传递给父组件,并在 CaseHeader videoComponentDidMount 中使用该值来设置状态。然后通过调用this.state.offsetHeight来访问offsetHeight属性?
关于javascript - 当子组件调用方法时,父引用为 null - ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46034824/