我有BaseComponent,所有其他组件都从该组件继承。但是,如果子组件具有componentDidMount()
,则不会调用父级componentDidMount()
。是否有任何方法可以在componentDidMount()
子组件之后始终调用父组件的componentDidMount()
?这是example。
答案 0 :(得分:0)
您可以使用“super()”函数来调用父实现。
componentDidMount() {
console.log('Child mounted.');
super();
}
但这被视为反模式。建议的方法是组合(详情here)。不幸的是,如果不知道你想要通过继承来实现什么,我们就无法通过组合告诉你一个替代方案。在使用您的示例时,可以执行类似这样的操作
class Animal extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log('Parent mounted.'); // Not working.
}
render() {
return (<div>{this.props.animalType}</div>);
}
}
class Dog extends React.Component {
componentDidMount() {
console.log('Child mounted.');
}
render() {
return (<Animal animalType="Dog" />);
}
}
React.render(<Dog />, document.body);
答案 1 :(得分:0)
在您的示例中,您的父组件Animal
实际上不是父组件,而是一个独立组件,因为无论如何您正在呈现Dog
组件。
这是componentDidMount
组件Animal
没有被调用的原因,实际上Animal component
本身没有被渲染,只是被定义。
为了使Dog
成为Animal
组件的子组件,请从父组件(Animal
)中呈现它并更改代码,如
class Animal extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log('Parent mounted.'); // Not working.
}
render() {
return (
<Dog/>
)
}
}
class Dog extends Animal {
componentDidMount() {
console.log('Child mounted.');
}
render() {
return <div>Dog.</div>;
}
}
React.render(<Animal />, document.body);
<强> JSFIDDLE 强>