跳到主要内容

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>支持状态: {JSON.stringify(isSupported)}</p>
      <p>请在至少两个标签页中打开此页面</p>
      <p>
        <b>频道:</b> reactuse-demo-channel
      </p>
      <p>
        <b>消息:</b> {data}<br/>
        <b>时间戳:</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.message}</p>}
    </div>
  );
}
结果

支持状态: true

请在至少两个标签页中打开此页面

频道: reactuse-demo-channel

消息:
时间戳: 0

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 (必填)-
ads via Carbon