React 组件通信--- Transfer Data in React
正常props父子传递 children props
class A extends Component {
state = {name:'tom'}
render() {
const {name} = this.state
return (
<div className="a">
<h3>我是A组件</h3>
<B name={name}/>
</div>
)
}
}
class B extends Component {
render() {
return (
<div className="b">
<h3>我是B组件,{this.props.name}</h3>
</div>
)
}
}render props
import React, { Component } from 'react'
export default class Parent extends Component {
render() {
return (
<div className="parent">
<h3>我是Parent组件</h3>
<A render={(name)=><B name={name}/>}/>
</div>
)
}
}
class A extends Component {
state = {name:'tom'}
render() {
const {name} = this.state
return (
<div className="a">
<h3>我是A组件</h3>
{this.props.render(name)}
</div>
)
}
}
class B extends Component {
render() {
return (
<div className="b">
<h3>我是B组件,{this.props.name}</h3>
</div>
)
}
}消息订阅-发布 pubs-sub
send data
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
export default class Search extends Component {
search = ()=>{
//获取用户的输入(连续解构赋值+重命名)
const {keyWordElement:{value:keyWord}} = this
//发送请求前通知List更新状态
PubSub.publish('pubKey',{isFirst:false,isLoading:true})
}
}get data
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
export default class List extends Component {
componentDidMount(){
this.token = PubSub.subscribe('pubKey',(_,stateObj)=>{
this.setState(stateObj)
})
}
componentWillUnmount(){
PubSub.unsubscribe(this.token)
}
}
集中式管理 redux
Refer to previous blog
生产者-消费者模式 context
import React, { Component } from 'react'
//创建Context对象
const MyContext = React.createContext()
const {Provider,Consumer} = MyContext
export default class A extends Component {
state = {username:'tom',age:18}
render() {
const {username,age} = this.state
return (
<div className="parent">
<h3>我是A组件</h3>
<h4>我的用户名是:{username}</h4>
<Provider value={{username,age}}>
<B/>
</Provider>
</div>
)
}
}
class B extends Component {
render() {
return (
<div className="child">
<h3>我是B组件</h3>
<C/>
</div>
)
}
}
/* class C extends Component {
//声明接收context
static contextType = MyContext
render() {
const {username,age} = this.context
return (
<div className="grand">
<h3>我是C组件</h3>
<h4>我从A组件接收到的用户名:{username},年龄是{age}</h4>
</div>
)
}
} */
function C(){
return (
<div className="grand">
<h3>我是C组件</h3>
<h4>我从A组件接收到的用户名:
<Consumer>
{value => `${value.username},年龄是${value.age}`}
</Consumer>
</h4>
</div>
)
}组件间的关系
父子组件:props
兄弟组件(非嵌套组件):消息订阅-发布、集中式管理
祖孙组件(跨级组件):消息订阅-发布、集中式管理、context