React pubsub-js means for transmitting values assembly Brothers

1 === "Technical raect components communicate with each other in two brothers used 
with message subscription (Subscribe) and release (publish) primary mechanisms s children s rai b pʌ b lɪ ʃ
There is a library can handle 
PubSubJS it is a third-party plug-ins  
 1) Download cnpm install pubsub-js -S my version "PubSub-JS": "^ 1.7.0" ,
 2) the introduction of import PubSub from the use of components that need. " pubsub-js "
  // id declare a unique id, or identifiers, provided identification is pubsub-js, must not be repeated
  // data The second parameter can also be passed an object that represents the content delivery
   PubSub.publish (id, data) began publishing

   PubSub.subscribe(id, callback(message, data){}) 订阅

 

 

Numbergo1 .js brothers assembly may pass a value to the assembly Numbergo2 .js
React Import, {from} the Component "REACT" 
Import from the PubSub "JS-PubSub" 

Export default class Numbergo1 the extends the Component {
     // send message: PubSub.publish (name, parameters) 

    State = { 
        ListItem: "I am from a component the ran " 
    } 
    
    chuandi = () => {
         // PubSub.publish (id, Data)   
        // ID declare a unique id, or the identifier provided to identify pubsub-js, must not repeat 
        // Data of two parameters of an object may pass 
        the let} = {ListItem the this .STATE // results 
        PubSub.publish ( 'mykeyvalue' , ListItem) 
 
    } 


    the render () {
        return (
            <div>
                <button onClick={this.chuandi}>按钮</button>
            </div>
           
        )
    }
}

 

Numbergo2.js
import React, { Component } from "react"
import PubSub from "pubsub-js"


export default class Numbergo2 extends Component {
    // 发送消息:PubSub.publish(名称, 参数)
    
    state={
        info:""
    }


    // 声明周期 组件完成挂载之后
    componentDidMount(){
        // mykeyvalue表示符  msg报错信息  data传递过来的数据
        PubSub.subscribe("mykeyvalue",(msg,data)=>{
            console.log("从另外一个组件从低过来的数据",data);
            this.setState({
                info: data
            })
        })
    }

   
    render() {
        // render使用state中的数据 必须要先解构构
        let {info}=this.state
        return (
            <div>
                ----{info}
            </div>

        )
    }
}

 

 

Guess you like

Origin www.cnblogs.com/IwishIcould/p/11621061.html