简体   繁体   English

当 web 组件属性异步更新时如何更新 React 道具?

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

I'm working on a React form.我正在处理一个 React 表单。 The web component part works fine, but as shown in the example, I'm having issues updating properties in the App component, when attributes are updated async later. web 组件部分工作正常,但如示例所示,当稍后异步更新属性时,我在更新 App 组件中的属性时遇到问题。

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

What am I missing to get the token value sent to when its updated async as demonstrated by the setTimeout on the host page?如主机页面上的 setTimeout 所示,当更新异步时,我缺少将令牌值发送到什么?

A few things I haven't played with before but 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM