父组件:
import React from "react"
import ComentList from "./ComentList"
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {name: 'Hhhhh’}
}
render() {
return (
<div>
<Child name={this.state.name}>
</Child>
</div>
)
}
}
export default Parent;
子组件
import React from "react"
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {name: props.name}
}
componentWillReceiveProps (nextProps) {
// 在接受父组件改变后的props需要重新渲染组件时用到的比较多
// 接受一个参数nextProps
// 通过对比nextProps和this.props,将nextProps的state为当前组件的state,从而重新渲染组件
console.log(nextProps)
this.setState({name: nextProps.name})
}
render() {
return (
<div className="child">
我是子组件
</div>
)
}
}
export default Child;