天天看點

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>
	);
}
           

繼續閱讀