简体   繁体   English

如何向 React 组件添加事件侦听器?

[英]How do I add an event listener to a React component?

I'm trying to build a React web app (v 16.13.0).我正在尝试构建一个 React Web 应用程序 (v 16.13.0)。 I want a flash message component, to display status after a form is submitted.我想要一个 flash 消息组件,在提交表单后显示状态。 If there is already something standard, that would be preferable, but since I can't find anything, I'm trying to roll my own using this -- https://medium.com/@jaouad_45834/building-a-flash-message-component-with-react-js-6288da386d53 .如果已经有一些标准的东西,那会更可取,但由于我找不到任何东西,我正在尝试使用它来推出我自己的 - https://medium.com/@jaouad_45834/building-a-flash- message-component-with-react-js-6288da386d53 Here's the component这是组件

import React, { useEffect, useState } from 'react';
import Bus from '../Utils/Bus';

import './index.css';

export const Flash = () => {
    let [visibility, setVisibility] = useState(false);
    let [message, setMessage] = useState('');
    let [type, setType] = useState('');

    useEffect(() => {
        Bus.addListener('flash', ({message, type}) => {
            setVisibility(true);
            setMessage(message);
            setType(type);
            setTimeout(() => {
                setVisibility(false);
            }, 4000);
        });


    }, []);

    useEffect(() => {
        if(document.querySelector('.close') !== null) {
            document.
            querySelector('.close').
            addEventListener('click', () => setVisibility(false));
        }
    })

    return (
        visibility && <div className={`alert alert-${type}`}>
                <span className="close"><strong>X</strong></span>
                <p>{message}</p>
            </div>
    )
}

Problem is, web site uses custom code, but doesn't show source for问题是,网站使用自定义代码,但不显示源代码

        Bus.addListener('flash', ({message, type}) => {
            setVisibility(true);
            setMessage(message);
            setType(type);
            setTimeout(() => {
                setVisibility(false);
            }, 4000);
        });

so my question is, how do I add an event listener to a React component?所以我的问题是,如何向 React 组件添加事件侦听器?

Edit: In response to the answer given, I created this file ...编辑:为了回应给出的答案,我创建了这个文件......

localhost:client davea$ cat src/Utils/Bus.js 
import EventEmitter from 'events';
export default new EventEmitter();

but re-compiling my module results in this error ...但是重新编译我的模块会导致此错误...

./src/components/Flash/index.js
Module not found: Can't resolve '../Utils/Bus' in '/Users/davea/Documents/workspace/chicommons/maps/client/src/components/Flash'

These are the first lines of the file above.这些是上面文件的第一行。 Note the second "import" where I'm importing "Bus" ...请注意我正在导入“总线”的第二个“导入”......

import React, { useEffect, useState } from 'react';
import Bus from '../Utils/Bus';

import './index.css';

export const Flash = () => {

The website included the code: https://medium.com/@jaouad_45834/building-a-flash-message-component-with-react-js-6288da386d53该网站包含代码: https : //medium.com/@jaouad_45834/building-a-flash-message-component-with-react-js-6288da386d53

To set that up, we need to create a new folder in our root directory and name it Utils and create on it a Bus.js file with will contains the following code:
import EventEmitter from 'events';
export default new EventEmitter();

This is all Bus.js is, a simple event emitter.这就是 Bus.js 的全部,一个简单的事件发射器。

You can also use react-toastify or useToasts for this.您也可以为此使用react-toastifyuseToasts

In order to show the flash message, you need to do something like the following.为了显示 flash 消息,您需要执行以下操作。

Bus.emit('flash', {type: 'danger', message: 'error occurred'}); 

I have used the code you have provided and mixed it with a dummy form.我使用了您提供的代码并将其与虚拟表单混合。 Upon submitting the form, the flash message appears successfully.提交表单后,闪现消息成功显示。

在此处输入图片说明

Live example & working code is here:现场示例和工作代码在这里:

https://codesandbox.io/s/dazzling-lamarr-k3cn5 https://codesandbox.io/s/dazzling-lamarr-k3cn5

Some notes:一些注意事项:

  • I have refactored and removed 2nd useEffect as it is inefficient and unnecessary.我已经重构并删除了 2nd useEffect,因为它效率低下且不必要。 The onClick can very well be applied to the close-span-element onClick 可以很好地应用于 close-span-element
  • If you are using redux, you can use create global Flash/Alert message and connect it to the store.如果您使用的是 redux,您可以使用 create global Flash/Alert message 并将其连接到 store。 Any redux-connected-component can simply work its own logic and dispatch an alert action and render different types of messages.任何 redux-connected-component 都可以简单地工作自己的逻辑并调度警报操作并呈现不同类型的消息。
  • Using ready made libraries are also cool.使用现成的库也很酷。

我认为你想要的是众所周知的Toaster,你可以使用像React Toastify [ https://github.com/fkhadra/react-toastify]这样的库,配置简单,定制化程度高

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 React 的类组件中向事件侦听器添加样式? - How can I add styling to an event listener in an class component in React? 如何将参数从组件传递到React中的事件侦听器? - How do I pass parameters from a component into an event listener in React? 如何使用 React 将事件监听器“更改”添加到输入元素? - How do I add event listener 'on change' to an input element with React? 我需要在每个反应组件中注册 window 事件侦听器吗? - do i need to register window event listener in each react component? 如何将我自己的事件侦听器添加到我的自定义 React Native 组件中? - How can I add my own event listener to my custom React Native component? 如何使用侦听器重构此 React 组件以使组件正常工作? - How do I refactor this React component with a listener, to make the component functional? 如何在 React 中添加事件监听器? - How to add event listener in React? 如何在 ReactJS 的父组件上设置事件侦听器? - How do I set an event listener on the parent component in ReactJS? 如何将 keyup 事件侦听器添加到 React 功能组件中的窗口,该组件仅在应用程序最初加载时添加? - How do you add an keyup event listener to window in a React functional component that only gets added when the app originally loads? 如何添加事件以响应组件? - How can I add an event to react component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM