• React组件间通信-sub/pub机制


    React生命周期第二个demo演示了兄弟组件的通信,需要通过父组件,比较麻烦;下面介绍sub/pub机制来事项组件间通信。

    项目结构:

    1、导包

    npm i pubsub-js

     

    2、UserSearch.jsx

    import React from 'react'
    import PubSub from 'pubsub-js'
    
    export default class UserSearch extends React.Component {
        state = {
            keyword: ''
        }
    
        render() {
            const { keyword, userList } = this.state
            return (
                <div>
                    <h3>搜索用户</h3>
                    <input type="text" placeholder="请输入搜索关键字" name="keyword" value={keyword} onChange={(e) => this.keywordInputOnChangeHandler(e)} />
                    <input type="button" value="开始搜索" onClick={() => this.searchClickHandler()} />
                </div>
            )
        }
    
        keywordInputOnChangeHandler = (e) => {
            const keyword = e.target.value
            this.setState({ keyword })
        }
    
        searchClickHandler = () => {
            const { keyword } = this.state
            console.log(`keyword.trim()=${keyword.trim()}`)
            if (!keyword.trim()) return
    
            // publish a topic asynchronously
            PubSub.publish('search', keyword);
        }
    }

    3、UserList.jsx

    import React from 'react'
    import PubSub from 'pubsub-js'
    import Axios from 'axios'
    
    export default class UserList extends React.Component {
        state = {
            userList: []
        }
    
        componentDidMount() {
            var mySubscriber = (msg, data) => {
                console.log(msg, data);
                console.log(`订阅search,接收到消息:${data}`)
                this.doSearch(data)
            };
    
            console.log('UserList组件钩子函数componentDidMount。。。');
            PubSub.subscribe('search', mySubscriber)
        }
    
        doSearch = (keyword) => {
            Axios.get(`http://localhost:4000/react-db-crud/user/search?keyword=${keyword}`)
                .then(res => {
                    if (res.data.code == 0) {
                        const userList = res.data.data
                        console.log(`userList=${JSON.stringify(userList)}`)
                        this.setState({ userList })
                    }
                })
        }
    
        render() {
            return (
                <div>
                    {
                        this.state.userList.map(user => <p>{user.id + "--" + user.name + "--" + user.age}</p>)
                    }
                </div>
            )
        }
    }
  • 相关阅读:
    java 24
    java 24
    java 24
    java 24
    一个用httpPost,get访问外网接口,参数json,返回json的示例
    几个强大的oracle自带函数,可根据日期算年纪,根据数值匹配字段
    sql对日期的处理,一个存储过程示例
    一条sql,有分页,表合并查询,多表连接,用于oracle数据库
    后台返回data直接在页面转换
    JQuery的$和其它JS发生冲突的快速解决方法
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/12035254.html
Copyright © 2020-2023  润新知