我有一个名为Parent的组件,其中还有另一个名为Child的组件:
<Parent>
<Child/>
</Parent>
所以生命周期如下:
- 父构造函数
- 父母的渲染()
- 子构造函数
- 孩子的渲染()
- 孩子装上了
- 已安装父级
我可以在步骤 2 之后和步骤 3 之前以某种方式进行额外的父初始化吗?
更新:
class ThirdPartyLib {
init(elementId) {
console.log(`initializing element: ${elementId}`);
// element with #id: elementId should exist!
// document.getElementById(elementId).style.color = "red";
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
console.log("Parent's constructor");
}
render() {
console.log("rendering Parent");
new ThirdPartyLib().init("parent");
return (
<div id="parent">Parent: {this.props.name}
<Child name="Sara"/>
</div>
);
}
componentDidMount() {
console.log("Parent is mounted");
}
}
class Child extends React.Component {
constructor(props) {
super(props);
console.log(`Child ${this.props.name} constructor`);
}
render() {
console.log(`rendering Child: ${this.props.name}`);
return <div>Child: {this.props.name}</div>
}
componentDidMount() {
console.log(`Child ${this.props.name} is mounted`);
}
}
ReactDOM.render(<Parent name="Bob"/>, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
在这里我做了一些简化——我不只是改变元素的颜色,我可以在componentDidMount()
方法中做到这一点。相反,ThirdPartyLib
细节决定了初始化顺序。在创建任何子元素之前,我必须在父元素出现在 DOM 之后立即对其进行初始化。
更具体地说,Parent
并Child
共享完全相同的ThirdPartyLib
类实例。我无法将初始化逻辑放入 Parent 的render()
函数中,因为该元素尚未在 DOM 中。同样,我无法按照评论中的建议初始化 'sParent
之前,因为's在 's之前执行。Child
componentDidMount()
Child
componentDidMount()
Parent