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 (必填) | - |
UseBroadcastChannel
Returns
UseBroadcastChannelReturn<D, P>
Arguments
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
options | 选项 | UseBroadcastChannelOptions (必填) | - |
UseBroadcastChannelReturn
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
isSupported | 是否支持 | boolean (必填) | - |
channel | 频道 | BroadcastChannel | undefined (必填) | - |
data | 数据 | D | undefined (必填) | - |
post | 发送数据 | (data: P) => void (必填) | - |
close | 关闭 | () => void (必填) | - |
error | 错误 | Event | null (必填) | - |
isClosed | 是否关闭 | boolean (必填) | - |
timeStamp | 时间戳 | number (必填) | - |