1

React Web アプリ (v 16.13.0) を構築しようとしています。フォームが送信された後にステータスを表示するために、フラッシュ メッセージ コンポーネントが必要です。すでに標準的なものがあればそれが望ましいのですが、何も見つからないので、これを使用して独自のものを作成しようとしています - https://medium.com/@jaouad_45834/building-a-flash- message-component-with-react-js-6288da386d53 . コンポーネントはこちら

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>
    )
}

問題は、Web サイトでカスタム コードを使用しているが、ソースが表示されないことです。

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

私の質問は、イベントリスナーを React コンポーネントに追加するにはどうすればよいですか?

編集:与えられた答えに応じて、私はこのファイルを作成しました...

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

しかし、モジュールを再コンパイルすると、このエラーが発生します...

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

これらは、上記のファイルの最初の行です。「バス」をインポートしている2番目の「インポート」に注意してください...

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

import './index.css';

export const Flash = () => {
4

3 に答える 3