美文网首页
[react]11、events

[react]11、events

作者: 史记_d5da | 来源:发表于2021-11-08 07:59 被阅读0次

    1、events的使用

    需要使用命令添加events库 yarn add events
    1、初始化实例对象const events = new EventEmitter()
    2、添加事件监听events. addListener("events_name", this.handleEventMessage);
    3、移除事件监听events.removeListener("events_name", this.handleEventMessage);

    import React, { PureComponent } from 'react'
    import {EventEmitter} from 'events'
    
    const events = new EventEmitter()
    class Home extends PureComponent {
        constructor(props) {
            super(props);
        }
        componentDidMount() {
            events.addListener("sayHello", this.handleEventMessage);
        }
    
        componentWillUnmount() {
            events.removeListener("sayHello", this.handleEventMessage);
        }
        render() {
            return (
                <div>
                    Profile
                </div>
            )
        }
    
        handleEventMessage(args) {
            console.log(args + "hello");
        }
    }
    
    class Profile extends PureComponent {
        render() {
            return (
                <div>
                    Profile
                    <button onClick={e =>this.sendEvent()}>点击发送消息</button>
                </div>
            )
        }
    
        sendEvent() {
            console.log("发送消息")
            events.emit("sayHello", "123");
        }
    }
    
    export default class App extends PureComponent {
        constructor(props) {
            super(props);
        }
        render() {
            return (
                <div>
                    <Profile />
                    <Home />
                </div>
            )
        }
    }
    

    相关文章

      网友评论

          本文标题:[react]11、events

          本文链接:https://www.haomeiwen.com/subject/coeezltx.html