使用继承时 Wicket 7 Link/Label 错误

Wicket 7 Link/Label error when using inheritance

我正在使用 Wicket 7 开发一个应用程序,该应用程序使用基页作为其他页面扩展的模板。

在基本页面上,我想要一个标签和一个 link 根据用户是否经过身份验证而变化的标签。

这是我的 BasePage.html:

<div wicket:id="chromeMenu">foo</div>
    <div>
        <h2 wicket:id="userGreeting"></h2>
        <h2><a href="#" wicket:id="loginLink"><span wicket:id="loginLabel"></span></a> </h2>
    </div>
<wicket:child/>

和 BasePage.java:

public BasePage() {
    super();

    add(new ChromeDropDownMenu("chromeMenu", buildMenu()));

    add(new Label("pageTitle", new StringResourceModel("page.title", this, null)));

    if(BasicAuthenticatedSession.get().isSignedIn()) {
        // Do stuff here
    } else {
        add(new Label("userGreeting", "Hello Visitor"));
        add(new Link("loginLink") {
            @Override
            public void onClick() {
                setResponsePage(LoginPage.class);
            }
        });
        add(new Label("loginLabel","Test"));
    }
}

HomePage 扩展了 BasePage。

HomePage.html

<wicket:extend/>

HomePage.java

public class HomePage extends BasePage {
    private static final long serialVersionUID = 1L;

    public HomePage() {
        super();

        setPageTitle(new StringResourceModel("page.title", this, new Model<Serializable>("Admin")));

        add(new Label("version", getApplication().getFrameworkSettings().getVersion()));

    }
}

HomePage 是 Wicket 应用程序返回的class。

当我尝试加载主页时,出现以下错误:

Last cause: Unable to find component with id 'loginLabel' in [Link [Component id = loginLink]]
    Expected: 'loginLink:loginLabel'.
    Found with similar names: 'loginLabel'

它指向 BasePage.html 中的 结构作为问题的根源。

我已经尝试了几种方法来解决这个问题,但都没有成功。我认为可能需要 add(Link).add(Label),但这也不起作用。

有什么关于我遗漏的想法吗?

问题在

add(new Link("loginLink") {
        @Override
        public void onClick() {
            setResponsePage(LoginPage.class);
        }
    });
    add(new Label("loginLabel","Test"));

Link 应该是标签的父级:

link = new Link("loginLink") {
    @Override
    public void onClick() {
        setResponsePage(LoginPage.class);
    }
};
link.add(new Label("loginLabel","Test"));
add(link);

一些额外的注意事项:

  • 如果 setResponsePage() 是您在 onClick()
  • 中唯一需要的东西,最好使用 BookmarkablePageLink
  • 使用 AbstractLink#setBody(IModel label) 代替 Link+Label

错误消息说明了一切。

Last cause: Unable to find component with id 'loginLabel' in [Link [Component id = loginLink]] Expected: 'loginLink:loginLabel'. Found with similar names: 'loginLabel'

Wicket 期望您的 Java 代码中的组件层次结构与您在 HTML 中编写的相同。在 BasePage.html 你有:

<h2><a href="#" wicket:id="loginLink"><span wicket:id="loginLabel"></span></a> </h2>

在 BasePage.java 代码中,您需要将 loginLabel 添加为 loginLink 组件的子项。

    Link loginLink = new Link("loginLink") {
        @Override
        public void onClick() {
            setResponsePage(LoginPage.class);
        }
    };
    add(loginLink);
    loginLink.add(new Label("loginLabel", "Test"));