【发布时间】: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”
发生了什么:
- 如果我只打开一个新选项卡,我不会在控制台中看到“GREEEENNNNNNN”
- 如果我打开另一个新选项卡,我可以在第一个选项卡的控制台中看到“GREEEENNNNNNNNN”
问题:如何将此值广播到新标签页?
【问题讨论】:
标签: reactjs react-hooks broadcast-channel