UPDATE
这个答案适用于React 15.目前的版本是17+,因此这可能是不相关的.
ORIGINAL
是的,componentDidMount
个子元素在父母面前被召唤.
Run the code below!
documentation states:
在初始渲染发生后立即调用一次,仅在客户端(而不是服务器上)上调用.在生命周期的这一点上,您可以访问子元素的任何引用(例如,访问底层DOM表示).child components的componentDidMount()
方法在父组件的componentDidMount()
方法之前被调用.
这是因为在渲染时,您应该能够引用任何内部/子 node ,但不接受try 访问父 node .
Run the code below.显示控制台输出.
var ChildThing = React.createClass({
componentDidMount: function(){console.log('child mount')},
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
var Parent = React.createClass({
componentDidMount: function(){console.log('parent')},
render: function() {
return <div>Sup, child{this.props.children}</div>;
}
});
var App = React.createClass({
componentDidMount: function(){console.log('app')},
render: function() {
return (
<div>
<Parent>
<ChildThing name="World" />
</Parent>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>