在Stencil Web组件中进行React渲染

时间:2019-04-18 22:00:29

标签: reactjs web-component react-dom stenciljs html-templates

这可能有点棘手-我想在通过Stencil准备的Web组件内部渲染React,但是我得到了“不变违规:目标容器不是DOM元素。”:

import { Component, Prop } from "@stencil/core";
import { format } from "../../utils/utils";
import ReactDOM from 'react-dom';
import React from "react";
import { LikeButton } from './../LikeButton';

const e = React.createElement;

@Component({
  tag: "my-component",
  styleUrl: "my-component.css",
  shadow: true
})
export class MyComponent {
  @Prop() first: string;
  @Prop() middle: string;
  @Prop() last: string;

  private getText(): string {
    return format(this.first, this.middle, this.last);
  }

  componentWillLoad() {
    console.log("here i am - the React render");
    const domContainer = document.querySelector("#like_button_container");
    ReactDOM.render(e(LikeButton), domContainer);
  }

  render() {
    return (
      <div>
        Hello, World! I'm {this.getText()}{" "}
        <div id="like_button_container">React container</div>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您可以使用@Element()装饰器,并使用它来查询domContainer下的shadowRoot元素。在这种情况下,shadowRoot需要@Element(),因为您已将shadow设置为true

import { Component, Element, Prop } from "@stencil/core";
import { format } from "../../utils/utils";
import ReactDOM from 'react-dom';
import React from "react";
import { LikeButton } from './../LikeButton';

const e = React.createElement;

@Component({
  tag: "my-component",
  styleUrl: "my-component.css",
  shadow: true
})
export class MyComponent {
  @Element() el: HTMLElement;
  @Prop() first: string;
  @Prop() middle: string;
  @Prop() last: string;

  private getText(): string {
    return format(this.first, this.middle, this.last);
  }

  componentWillLoad() {
    const domContainer = this.el.shadowRoot.querySelector("#like_button_container");
    ReactDOM.render(e(LikeButton), domContainer);
  }

  render() {
    return (
      <div>
        Hello, World! I'm {this.getText()}{" "}
        <div id="like_button_container">React container</div>
      </div>
    );
  }
}

在stenciljs开发模式下运行时出现间歇性问题。刷新页面时,可能是由于缓存引起的问题,但是如果我通过保存包含此代码的stenciljs组件文件触发了重新加载,则通常可以正常工作。这可能与stencil-dev-server而不是代码有关。

希望有帮助!