使用 hyperHTML 和 hyperhtml-app 中的链接进行导航

Navigation with links in hyperHTML and hyperhtml-app

我刚刚开始使用 hyperHTML。我正在构建一个需要路由的小应用程序,所以我将它与 hyperhtml-app 结合在一起。

我正在尝试在视图上设置点击处理程序来处理对锚点元素的点击并让它们通过路由器进行导航。以下是可行的,但看起来很复杂,我想我缺少更好的方法。你能推荐一个更好的方法吗?

import hyper from 'hyperhtml';
import hyperApp from 'hyperhtml-app';

const app = hyperApp();

class Welcome extends hyper.Component {
  render() {
    return this.html`
      <h1>Welcome</h1>
      <a href="/settings" onclick=${this}>settings</a>
    `;
  }

  onclick(e) {
    if (e.target instanceof HTMLAnchorElement) {
      e.preventDefault();
      app.navigate(e.target.attributes.href.value);
    }
  }
}

class Settings extends hyper.Component {
  render() {
    return this.html`<h1>Settings</h1>`;
  }
}

app.get('/', () => hyper(document.body)`${new Welcome()}`);

app.get('/settings', () => hyper(document.body)`${new Settings()}`);

app.navigate('/');

路由器的目的是为您处理导航。

实际上只有当您不希望路由器工作时才需要阻止默认设置。

我创建了一个 Code Pen example 显示完全相同的代码,甚至根本不影响点击。

最后一点,如果你想保持之前页面的状态,你应该处理一次,然后在每次渲染时重复使用它们。

const page = {
  welcome: new Welcome,
  settings: new Settings
};

app.get('/', () => hyper(document.body)`${page.welcome}`);

app.get('/settings', () => hyper(document.body)`${page.settings}`);

如果您有任何其他问题,请随时提问。

此致