React组件只需点击按钮即可在Vaadin 7中添加



我有一个vaadin7应用程序,我正试图将一个示例react应用程序集成到该应用程序中。当我在按钮点击中实现React组件创建时,它工作正常。但如果我把代码放在按钮点击之外,它就不起作用了。它显示错误";未捕获的TypeError:无法读取null的属性"appendChild"位于Module.11(索引.js:9(在u(引导程序:84(at t(引导程序:45(在Array.r〔as push〕(引导程序:32(在main.90a85973.chunk.js:1";检查时。

在vaadin应用程序中,我正在创建名为"的div;根";在示例react应用程序的index.js中,我试图获得从vaadin创建的根div,并添加";反应根";至";根";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());

我的Reactcomponent

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

ReactComponentState

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

ReactComponentConnector.js

window.com_p1_p2_ReactComponent = function () {

}

我的示例react应用程序的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()实例。

最新更新