1.父组件:
// 父子组件传参
import React, { Component } from "react";
//引入子组件
import Child from './Child'
export default class Father extends Component {
constructor() {
super();
this.state = {
count: 10
}
}
//改变count的值
changeFather = ()=> {
console.log('changeFather函数调用了');
this.setState({
count:this.state.count+1
})
}
render() {
let {count} = this.state;
//也可以传递一个解构
let oDiv = <div>我是一个HTML结果</div>
return (
<div>
<p>我是Father组件</p>
{/*传递数据 msg='我是字符串' */}
<Child oDiv={oDiv} msg='我是字符串' count={count} changeFather={this.changeFather}>
<h3>我是从父组件传递下去的h3标签</h3>
<h2>我是第二个传递的</h2>
<h1>我是第三个传递的</h1>
</Child>
</div>
)
}
}
2.子组件:
import React, { Component } from "react";
export default class Child extends Component {
//props 接收父组件传递的数据 constructor 和 super 都需要要接
constructor(props) {
//props 只能读取,不能修改
console.log(props);
super(props);
}
//更新后生命周期
componentDidUpdate (){
console.log('子组件componentDidUpdate 执行');
//在子组件方法里面使用props传递下来的参数
console.log('父组件传递下来的msg',this.props.msg);
}
//在子组件里面修改父组件的count
changeFather = ()=> {
this.props.changeFather()
}
render() {
//直系子元素 react的插槽
console.log('this.props.children',this.props.children);
return (
<div>
<p>我是Child组件</p>
<p>父组件传下来的msg:{this.props.msg}</p>
<p>父组件传下来的count:{this.props.count}</p>
<button onClick={this.changeFather}>在子组件里面修改父组件的count</button>
{/* 接收父组件传递下来的结构 */}
{this.props.children[1]}
// 以下是传递的oDiv的值
{this.props.oDiv}
</div>
)
}
}