跳到主要内容

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