如下组件结构: A组件下面有B1和B2两个组件 B1下面有Grandson1组件
import logo from './logo.svg';
import './App.css';
import React from 'react';
class App extends React.Component {
constructor() {
super();
console.log('constructor App');
this.state = {
num: 0
};
this.click = this.click.bind(this);
}
componentWillMount() {
console.log('componentWillMount App');
}
componentDidMount() {
console.log('componentDidMount App');
}
click() {
this.setState({ num: this.state.num + 1 });
}
render() {
console.log('render App');
return (
<div>
<input onClick={this.click}></input>
<Child1 />
<Child2 />
</div>
);
}
}
class Child1 extends React.Component {
constructor() {
super();
console.log('constructor Child1');
}
componentWillMount() {
console.log('componentWillMount Child1');
}
componentDidMount() {
console.log('componentDidMount Child1');
}
render() {
console.log('render Child1');
return (
<div>
B1
<Grandson1 />
</div>
);
}
}
class Child2 extends React.Component {
constructor() {
super();
console.log('constructor Child2');
}
componentWillMount() {
console.log('componentWillMount Child2');
}
componentDidMount() {
console.log('componentDidMount Child2');
}
render() {
console.log('render Child2');
return <div>B2</div>;
}
}
class Grandson1 extends React.Component {
constructor() {
super();
console.log('constructor Grandson1');
}
componentWillMount() {
console.log('componentWillMount Grandson1');
}
componentDidMount() {
console.log('componentDidMount Grandson1');
}
render() {
console.log('render Grandson1');
return <div>Grandson1</div>;
}
}
export default App;
执行结果如下:
每次修改父组件的state:会执行如下: