【问题标题】:React with BroadcastChannel与 BroadcastChannel 反应
【发布时间】:2022-07-07 05:18:02
【问题描述】:

在 React 应用程序中,我单击按钮打开新选项卡。 当我打开新标签时,我想将一些数据传递给新标签。

我的按钮组件中的代码

const channel = new BroadcastChannel('color');

const handleClick = () => {
 ...
 channel.postMessage('GREEEENNNNNNNNN');
}

来自新标签组件的代码

const [color, setColor] = React.useState('');

const channel = new BroadcastChannel('color');
  React.useEffect(() => {
    channel.onmessage = (msg) => setColor(msg.data);
  }, [channel]);

  console.log('color <========', color); // just to see that this is working

我的期望:我在新标签页的控制台中看到“GREEEENNNNNNNNN”

发生了什么:

  1. 如果我只打开一个新选项卡,我不会在控制台中看到“GREEEENNNNNNN”
  2. 如果我打开另一个新选项卡,我可以在第一个选项卡的控制台中看到“GREEEENNNNNNNNN”

问题:如何将此值广播到新标签页?

【问题讨论】:

    标签: reactjs react-hooks broadcast-channel


    【解决方案1】:

    宣布香奈儿

    const channel = useMemo(() => new BroadcastChannel('color'), []);
    

    接收消息

    useEffect(() => {
            channel.addEventListener('message', (event) => {
                 setColor(msg.data.color);
    
            });
        }, []);
    

    发送消息

    channel.postMessage({
                color: 'red'
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 2022-01-26
      • 1970-01-01
      • 2021-12-07
      • 2021-05-05
      相关资源
      最近更新 更多