import React, { PureComponent } from 'react'
import './index.css'
export default class Parent extends PureComponent {
state = { carName: '奔驰' }
changeCar = ()=>{
this.setState({carName:'五菱'})
}
// shouldComponentUpdate(nextProps,nextState){
// console.log('this.state:',this.state,'this.props:',this.props,'nextProps:',nextProps,'nextState:',nextState);
// return !(this.state.carName === nextState.carName)
// }
render() {
console.log('Parent-render');
const { carName } = this.state
return (
<div className='parent'>
<h5>parent组件</h5>
<span>我的车是:{carName}</span>
<button onClick={this.changeCar}>换车</button>
<Child car='木马'></Child>
</div>
)
}
}
class Child extends PureComponent {
// shouldComponentUpdate(nextProps,nextState){
// console.log('this.state:',this.state,'this.props:',this.props,'nextProps:',nextProps,'nextState:',nextState);
// return !(this.props.car === nextProps.car)
// }
render() {
console.log('Child-render');
return (
<div className='child'>
<h5>child组件</h5>
<div>Child组件从Parent组件拿到的车是:{this.props.car}</div>
</div>
)
}
}
样式文件:
.parent{
width: 500px;
background-color: aqua;
padding: 20px;
}
.child{
width: 90%;
background-color:bisque;
padding: 20px;
margin-top: 30px;
}
效果实现: