Web组件属性异步更新时如何更新React props?

How to update React props when web component attributes are updated async?

我正在处理 React 表单。 Web 组件部分工作正常,但如示例所示,我在 App 组件中更新属性时遇到问题,当稍后异步更新属性时。

代码示例:https://stackblitz.com/edit/react-ts-nypnbz?file=index.tsx

当主机页面上的 setTimeout 显示更新异步时,我缺少什么来获取发送到的令牌值?

一些我以前没玩过但 this works.

import React, { useState } from "react";
import { render } from "react-dom";

interface AppProps {
  name: string | null;
  token: string | null;
}

const App = ({ name, token }: AppProps) =>
  token ? (
    <span>
      {name} has token {token}
    </span>
  ) : (
    <span>{name} has no token</span>
  );

class SignupForm extends HTMLElement {
  setToken;

  FormApp = (props: AppProps) => {
    const [token, updateToken] = useState("");
    this.setToken = updateToken;
    return <App name={props.name} token={token} />;
  };

  connectedCallback() {
    const mountPoint = document.createElement("div");
    this.attachShadow({ mode: "open" }).appendChild(mountPoint);
    render(<this.FormApp name={this.name} token={this.token} />, mountPoint);
  }

  get name() {
    return this.getAttribute("name");
  }

  get token() {
    return this.getAttribute("token");
  }

  static get observedAttributes() {
    return ["name", "token"];
  }

  attributeChangedCallback(name: string, oldValue: string, newValue: string) {
    console.log(
      `${name}'s value has been changed from ${oldValue} to ${newValue}`
    );
    if (typeof this.setToken === "function") {
      this.setToken(newValue);
    }
  }
}

if (!customElements.get("signup-form")) {
  customElements.define("signup-form", SignupForm);
}