A: the preface

During project development, it is common to encounter value passing between components.

  • The first is passing values between parent and child components

    • Parent components pass values to child components

    Bind the values to be passed to the child component labels in the parent component

    render() { const {todos} = this.state return ( <div className="todo-container"> <div className="todo-wrap"> <Header addToDo={this.addToDo}/> <List todos={todos} delleToDo={this.delleToDo} updateTodo={this.updateTodo}/> <Footer todos={todos} clearAllDone={this.clearAllDone} checkAllTodo={this.checkAllTodo}/> <button OnClick ={this.handledhttp}> </button> </div> </div>)}Copy the code
    • Subcomponent reception

    Receive content via props, for example:

    	let {todos,clearAllDone} = this.props
    Copy the code
  • The second type of value transfer between sibling components

Of course, we could define the state of child A in the parent, and then pass the state to child B, which would result in the parent code getting bigger and bigger. PubSubjs can solve this problem.

Two: use of PubSub

1) Install PubSub

yarn add pubsub-js

2) Basic use of Pubsub

Publish in the component Head

import React,{ Component } from "react";

import PubSub from 'pubsub-js'

export default class Heard extends Component {
    handleTodoData = ()=>{
       let {addTodoElement} = this
        PubSub.publish('addTodoList',{name:addTodoElement.value})

    }
    render(){
        return (
            <div>
                <input ref={(elementNode)=>this.addTodoElement=elementNode} placeholder="请输入内容"/>
                <button onClick={this.handleTodoData}>添加数据</button>
            </div>
        )
    }
}
Copy the code

Subscribe in the component Main

import React,{ Component } from "react"; import PubSub from 'pubsub-js' export default class Main extends Component { componentDidMount(){ Subscribe ('addTodoList',(MSG,data)=> {console.log(' subcomponent subscribe data: ', data)})} render () {return (< div > < ul > < li > 1 < / li > < / ul > < / div >)}}Copy the code