渲染开始后更改子组件的可见性

Changing the the visibility of a child component after rendering started

我有一个由两个子组件A和B组成的组件。但是,显示A或B的可见性只能在页面渲染开始后才能确定。我尝试这样做但返回了以下错误:

Cannot modify component hierarchy after render phase has started

那么,在我的案例中,有什么方法可以更改子组件的可见性吗?

我不确定我是否理解你的问题。 我假设您有 2 个容器并且只想显示其中一个。如果是这种情况,您可以简单地扩展 onConfigure() 方法并按照您希望的方式更改可见性。此方法将在每次渲染期间调用一次,因此优于扩展 isVisible() 方法(在每次请求期间调用多次)。

private IModel<Boolean> switchModel = Model.of(Boolean.FALSE);

@Override
protected void onInitialize() {
    super.onInitialize();

    WebMarkupContainer container1 = new WebMarkupContainer("container1") {
        @Override
        protected void onConfigure() {
            super.onConfigure();
            setVisible(Boolean.TRUE.equals(switchModel.getModelObject()));
        }
    };
    add(container1);

    WebMarkupContainer container2 = new WebMarkupContainer("container2") {
        @Override
        protected void onConfigure() {
            super.onConfigure();
            setVisible(Boolean.FALSE.equals(switchModel.getModelObject()));
        }
    };
    add(container2);
}