繁体   English   中英

仅在按钮单击时在 Vaadin 7 中添加 React 组件

[英]React Component getting added in Vaadin 7 only on button click

我有一个 vaadin7 应用程序,我正在尝试将示例 React 应用程序集成到该应用程序中。 当我在按钮单击中实现 React 组件创建时,它工作正常。 但是如果我把代码放在按钮点击之外,它就不起作用。 它显示错误“Uncaught TypeError:无法在 u (bootstrap:84) at t (bootstrap:45) at Array.r [as push] (bootstrap :32) at main.90a85973.chunk.js:1" 同时检查。

在 vaadin 应用程序中,我正在创建名为“root”的 div,在示例 React 应用程序的 index.js 中,我试图获取从 vaadin 创建的根 div 并将“react-root”附加到“root”div 以适应我的 vaadin 布局中的 react 应用程序。

请在下面找到 vaadin ui 的代码

CustomLayout layout = null;
        try {
            String dynamicHtml = "<div id=\"root\"></div>";
            layout = new CustomLayout(new ByteArrayInputStream(dynamicHtml.getBytes()));
            System.out.println("JS Layout");
        } catch (IOException e) {
            System.out.println("could not create custom layaout"+ e);
        }
        uimainLayout.addComponent(layout);
        

//如果在按钮点击中添加了以下4行代码,则在点击按钮时,reactcomponent在布局内部正确呈现。 否则它会显示“未捕获的类型错误:无法读取 null 的属性 'appendChild'”

        VerticalLayout jsmainLayout = new VerticalLayout();
        ReactComponent reactComponent=new ReactComponent();
        jsmainLayout.addComponent(reactComponent);
        uimainLayout.addComponent(jsmainLayout);

        getMainLayout().addComponent(uimainLayout);
        setCompositionRoot(getMainLayout());

我的反应组件

@JavaScript({"<ip:port>/static/js/2.1f3e22a9.chunk.js","<ip:port>/static/js/3.583f7bad.chunk.js","<ip:port>/static/js/runtime-main.23689a58.js","<ip:port>/static/js/main.90a85973.chunk.js","ReactComponentConnector.js"})
@StyleSheet("<ip:port>/static/css/main.a617e044.chunk.css")
public class ReactComponent extends AbstractJavaScriptComponent {
    public ReactComponent() {
         System.out.println("Inside ReactComponent");
        
    }
    @Override
    protected ReactComponentState getState() {
        return (ReactComponentState) super.getState();
    }
}

反应组件状态

public class ReactComponentState extends JavaScriptComponentState {
    private static final long serialVersionUID = -3283446856435450054L;
}

ReactComponentConnector.js

window.com_p1_p2_ReactComponent = function () {

}

我的示例反应应用程序的 Index.js

const rootEl = document.createElement('div')
rootEl.setAttribute('id', 'react-root');
//error points to the below line
const parentEl =document.getElementById('root');
parentEl.appendChild(rootEl)

ReactDOM.render(
    <App />
  ,
  rootEl
);
reportWebVitals();

目前尚不清楚究竟是什么触发了运行为index.js列出的代码,但它似乎是在自定义布局的内容初始化之前运行的。 这样,id 为root元素不存在,这将导致报告的错误。

我假设创建是通过 JS 连接器初始值设定项内部的new ReactComponent(this.getElement())进行的。 如果是这种情况,那么他们的问题原因是这两个操作(设置自定义布局内容和初始化 JS 连接器)是在同一个批次中发送到浏览器的,但连接器在较早的阶段被初始化。 如果 JS 组件是通过单击侦听器触发的批处理发送,那么这将不成问题。

要解决此问题,您可以使用直接元素引用,而不是依赖getElementById与自定义布局内容中定义的 id 相结合。 最简单的方法是,如果您要重组以使用现在传递给 ReactComponent 构造函数的 this.getElement this.getElement()实例。

暂无
暂无

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

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