【问题标题】:How to reimplement material.io components in hyperHTML?如何在 hyperHTML 中重新实现 material.io 组件?
【发布时间】:2017-09-25 17:50:28
【问题描述】:

我正在查看这个关于 material.io 组件如何与 React 组件实现/集成的 React 示例:

https://github.com/material-components/material-components-web/blob/master/framework-examples/react/src/Checkbox.js

我想知道如何处理 hyperHTML,因为在 hyper.Component 中没有像 componentDidMount 或 componentWillUnmount 这样的生命周期事件调用。

据说我可以在render 调用之后执行此操作,但这通常是从组件外部调用的。

【问题讨论】:

    标签: javascript material-design single-page-application hyperhtml


    【解决方案1】:

    抱歉,我现在才看到这个。

    我想澄清几件事:

    在 hyper.Component 中没有像 componentDidMount 或 componentWillUnmount 这样的生命周期事件调用。

    如果您尝试最新版本,或者假设是 1.10+,您将能够在每个 hyper.Component 类定义中定义 onconnected(evt) { ... } 和 ondisconnected(evt) { ... } 方法。

    这是一个相当新的功能,遗憾的是尚未记录。但它提供了像自定义元素 connectedCallback 和 disconnectedCallback 方法一样行为所需的一切(请记住,还有一个 HyperHTMLElement project 可以创建真正的自定义元素)。

    以下是一个基本示例:

    import {Component} from 'hyperhtml';
    
    class Clock extends Component {
    
      update() {
        this.time = (new Date).toLocaleTimeString();
        this.render();
      }
    
      // equivalent of Custom Elements connectedCallback
      onconnected() {
        console.log('start time');
        this.update();
        this.timer = setInterval(() => this.update(), 1000);
      }
    
      // equivalent of Custom Elements disconnectedCallback
      ondisconnected() {
        console.log('end time');
        clearInterval(this.timer);
      }
    
      render() { return this.html`
        <p
          onconnected=${this}
          ondisconnected=${this}
        >
          ${this.time}
        </p>`;
      }
    }
    

    我希望这会给你足够的力量来复制材料示例。


    我想澄清的另一部分:

    据说我可以在调用渲染后执行此操作,但这通常是从组件外部调用的。

    这并不完全正确。是的,component.render() 会在需要时自动调用,但重要的是您返回的内容。

    我使用的代码与之前 Clock 示例中使用的代码相同:

    // same code as before
      render() {
        const p = this.html`
        <p
          onconnected=${this}
          ondisconnected=${this}
        >
          ${this.time}
        </p>`;
    
        // you have a <p> element here
        // you can do whatever you want
        // example:
        p.addEventListener('click', console.log);
    
        // now you should return it
        return p;
      }
    // rest of the code
    

    如您所见,您始终可以与渲染的节点进行交互。毕竟,hyperHTML 所做的只是创建您编写的内容,仅此而已。

    我希望这些说明可以帮助您继续前进。 最后,在这里回答其他问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 2021-10-12
      • 2020-04-30
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多