天天看点

React中组件的父子通信

父子通信,顾名思义就是父组件将自己的状态传递给子组件,子组件当做属性来接收,当父组件更改自己状态的时候,子组件接收到的属性就会发生改变。在这里,将举例类组件和函数式组件的父子通信。

类组件的父子通信

App.js

import React, { Component } from "react";

// 父组件App
export default class App extends Component {
	constructor(props) {
		super(props);
		this.state = {
			msg: "类组件的父子通信",
		};
	}

	render() {
		return (
			<div>
				<ChildCpn msg={this.state.msg}></ChildCpn>
			</div>
		);
	}
}

// 子组件ChildCpn
class ChildCpn extends Component {
	render() {
		const { msg } = this.props;
		return <h2>{msg}</h2>;
	}
}
           

函数组件的父子通信

App.js

import React, { Component } from "react";

// 父组件App
export default class App extends Component {
	constructor(props) {
		super(props);
		this.state = {
			msg: "函数组件的父子通信",
		};
	}

	render() {
		return (
			<div>
				<ChildCpn msg={this.state.msg}></ChildCpn>
			</div>
		);
	}
}

// 子组件ChildCpn
function ChildCpn(props) {
	return (
		<div>
			<h2>{props.msg}</h2>
		</div>
	);
}
           

继续阅读