在使用react的,不可避免的組件間的消息傳遞
1:父組件向子組件傳值(通常的是父組件向子組件傳遞props,子組件得到props后進(jìn)行對應(yīng)的處理)
App.js(父組件)
import React,{ Component } from "react";
import Sub from "./SubComponent.js";
export deafault class APP extents Component{
reader(){
return (`<div>
<Sub title = "今年過節(jié)不收禮" />
</div>`)
}
}
SubComponents.js(子組件)
import React,{ Component } from "react";
const Sub=(props)=>{
return(
<h1>{props.title}</h1>
)
}
2:子組件向父組件傳值( 父組件將一個函數(shù)作為 props 傳遞給子組件,子組件調(diào)用該回調(diào)函數(shù),便可以向父組件通信不铆。)
SubComponents.js
import React from 'react'
const Sub=(props)=>{
const cb=(msg)=>{
return()=>{
prop.callback(msg)
}
}
return(
<div>
<button onClick = { cb("我們通信把") }>點擊我</button>
</div>
)
}
export default Sub;
App.js
import Sub from "./SubComponent.js";
import React,{ Component } from "react";
callback(msg){console.log(msg)}
render(){
return(
<div>
<Sub callback={this.callback.bind(this)}> </Sub>
</div>
)
}
3:跨級組件之間的通信
所謂跨級組件通信顽腾,就是父組件向子組件的子組件通信,向更深層的子組件通信蹋宦」咄耍跨級組件通信可以采用下面兩種方式:
1: 中間組件層層傳遞 props
2: 使用 context 對象
對于第一種方式赌髓,如果父組件結(jié)構(gòu)較深,那么中間的每一層組件都要去傳遞 props,增加了復(fù)雜度春弥,并且這些 props 并不是這些中間組件自己所需要的。不過這種方式也是可行的叠荠,當(dāng)組件層次在三 層以內(nèi)可以采用這種方式匿沛,當(dāng)組件嵌套過深時,采用這種方式就需 要斟酌了榛鼎。
使用 context 是另一種可行的方式逃呼,context 相當(dāng)于一個全局變量,是一個大容器者娱,我們可以把要通信的內(nèi)容放在這個容器中抡笼,這樣一來,不管嵌套有多深黄鳍,都可以隨意取用推姻。
使用 context 也很簡單,需要滿足兩個條件:
1:上級組件要聲明自己支持 context框沟,并提供一個函數(shù)來返回相應(yīng)的 context 對象
2:子組件要聲明自己需要使用 context
APP.JS
import React, { Component } from 'react';
import PropTypes from "prop-types";
import Sub from "./Sub";
import "./App.css";
export default calss App extents Component{
//父組件聲明自己支持content
static childContentTypes={
color:Proptypes.string
callback:propsTypes.func
}
//父組件提供一個函數(shù)藏古,用來返回相應(yīng)的content 對象
getchildContent(){
return{
color:"red"
callback:this.callback.bind(this)
}
}
callback(msg){
console.log(msg)
}
render(){
return(
<div>
<Sub></Sub>
</div>
);
}
}
Sub.js
import React from "react";
import SubSub from "./SubSub";
const Sub = (props) =>{
return(
<div>
<SubSub />
</div>
);
}
export default Sub;
SubSub.js:
import React,{ Component } from "react";
import PropTypes from "prop-types";
export default class SubSub extends Component{
// 子組件聲明自己需要使用 context
static contextTypes = {
color:PropTypes.string,
callback:PropTypes.func,
}
render(){
const style = { color:this.context.color }
const cb = (msg) => {
return () => {
this.context.callback(msg);
}
}
return(
<div style = { style }>
SUBSUB
<button onClick = { cb("我胡漢三又回來了!") }>點擊我</button>
</div>
);
}
}
如果是父組件向子組件單向通信忍燥,可以使用變量拧晕,如果子組件想向父組件通信,同樣可以由父組件提供一個回調(diào)函數(shù)梅垄,供子組件調(diào)用厂捞,回傳參數(shù)。
在使用 context 時队丝,有兩點需要注意:
父組件需要聲明自己支持 context靡馁,并提供 context 中屬性的 PropTypes
子組件需要聲明自己需要使用 context冯痢,并提供其需要使用的 context 屬性的 PropTypes
父組件需提供一個 getChildContext 函數(shù)队秩,以返回一個初始的 context 對象
如果組件中使用構(gòu)造函數(shù)(constructor),還需要在構(gòu)造函數(shù)中傳入第二個參數(shù) context胜臊,并在 super 調(diào)用父類構(gòu)造函數(shù)是傳入 context吞加,否則會造成組件中無法使用 context裙犹。
...
constructor(props,context){
super(props,context);
}
import React, { Component } from 'react';
import PropTypes from "prop-types";
import Sub from "./Sub";
import "./App.css";
export default class App extends Component{
constructor(props) {
super(props);
this.state = {
color:"red"
};
}
// 父組件聲明自己支持 context
static childContextTypes = {
color:PropTypes.string,
callback:PropTypes.func,
}
// 父組件提供一個函數(shù),用來返回相應(yīng)的 context 對象
getChildContext(){
return{
color:this.state.color,
callback:this.callback.bind(this)
}
}
// 在此回調(diào)中修改父組件的 state
callback(color){
this.setState({
color,
})
}
render(){
return(
<div>
<Sub></Sub>
</div>
);
}
}
在子組件的 cb 方法中衔憨,傳入相應(yīng)的顏色參數(shù)叶圃,就可以改變 context 對象了,進(jìn)而影響到子組件:
...
return(
<div style = { style }>
SUBSUB
<button onClick = { cb("blue") }>點擊我</button>
</div>
);
...
context 同樣可以應(yīng)在無狀態(tài)組件上践图,只需將 context 作為第二個參數(shù)傳入:
import React,{ Component } from "react";
import PropTypes from "prop-types";
const SubSub = (props,context) => {
const style = { color:context.color }
const cb = (msg) => {
return () => {
context.callback(msg);
}
}
return(
<div style = { style }>
SUBSUB
<button onClick = { cb("我胡漢三又回來了掺冠!") }>點擊我</button>
</div>
);
}
SubSub.contextTypes = {
color:PropTypes.string,
callback:PropTypes.func,
}
export default SubSub;
4:非嵌套組件之間通信(非嵌套組件,就是沒有任何包含關(guān)系的組件,包括兄弟組件以及不在同一個父級中的非兄弟組件德崭。對于非嵌套組件斥黑,可以采用下面兩種方式:利用二者共同父組件的 context 對象進(jìn)行通信使用自定義事件的方式)
App.js
1:我們需要使用一個 events 包:(npm install events --save)
2:新建一個 ev.js,引入 events 包眉厨,并向外提供一個事件2對象锌奴,供通信時使用:
import { EventEmitter } from "events";
export default new EventEmitter();
import React, { Component } from 'react';
import Foo from "./Foo";
import Boo from "./Boo";
import "./App.css";
export default class App extends Component{
render(){
return(
<div>
<Foo />
<Boo />
</div>
);
}
}
Foo.js:
import React,{ Component } from "react";
import emitter from "./ev"
export default class Foo extends Component{
constructor(props) {
super(props);
this.state = {
msg:null,
};
}
componentDidMount(){
// 聲明一個自定義事件
// 在組件裝載完成以后
this.eventEmitter = emitter.addListener("callMe",(msg)=>{
this.setState({
msg
})
});
}
// 組件銷毀前移除事件監(jiān)聽
componentWillUnmount(){
emitter.removeListener(this.eventEmitter);
}
render(){
return(
<div>
{ this.state.msg }
我是非嵌套 1 號
</div>
);
}
}
Boo.js:
import React,{ Component } from "react";
import emitter from "./ev"
export default class Boo extends Component{
render(){
const cb = (msg) => {
return () => {
// 觸發(fā)自定義事件
emitter.emit("callMe","Hello")
}
}
return(
<div>
我是非嵌套 2 號
<button onClick = { cb("blue") }>點擊我</button>
</div>
);
}
}