useBroadcastChannel
useBroadcastChannel
是一个允许你在组件中使用 BroadcastChannel API
的 hook。
Usage
实时编辑器
function Demo() { const { isSupported, data, post, error,timeStamp } = useBroadcastChannel({ name: "reactuse-demo-channel", }); const [message, setMessage] = useState(""); useEffect(() => { if (isSupported) { alert(data); } }, [data]); return ( <div> <p>Supported: {JSON.stringify(isSupported)}</p> <p>Please open this page in at least two tabs</p> <p> <b>Channel:</b> reactuse-demo-channel </p> <p> <b>Message:</b> {data}<br/> <b>TimeStamp:</b> {timeStamp} </p> <input value={message} onChange={(event) => { setMessage(event.currentTarget.value); }} /> <button onClick={() => post(message)} style={{ cursor: isSupported ? "pointer" : "not-allowed", }} > 发送 </button> {error && <p>Error: {error.message}</p>} </div> ); }
结果
Loading...
API
UseBroadcastChannelOptions
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
name | 频道名称 | string (必填) | - |