当web组件属性异步更新时,如何更新React props ?



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

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

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

一些我以前没有玩过的东西,但这是可行的。

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);
}

最新更新