[英]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 所示,當更新異步時,我缺少將令牌值發送到什么?
一些我以前沒有玩過的東西,但這很有效。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.