【发布时间】:2019-11-05 05:21:48
【问题描述】:
我基于LitElement开始了一个项目 有很多组件相互嵌套,假设我们有这样的结构:
根组件是my-app
import { LitElement, html, customElement, query } from 'lit-element';
import './my-form';
import './my-view';
import { MyView } from './my-view';
@customElement('my-app')
export class MyApp extends LitElement {
@query('my-view') private myView?: MyView;
private handleCountChange(e: CustomEvent<{ count: number }>) {
if (!this.myView) throw 'my-view not found!';
this.myView.count = e.detail.count;
}
render() {
return html`
<my-form @countChanged=${this.handleCountChange}></my-form>
<my-view></my-view>
`;
}
}
如你所见,我们有两个组件:my-form
import { LitElement, html, customElement, property } from 'lit-element';
@customElement('my-form')
export class MyForm extends LitElement {
@property({ type: Number }) count: any = 0;
private updateCount(e: KeyboardEvent) {
this.count = (<HTMLInputElement>e.target).value;
this.dispatchEvent(
new CustomEvent('countChanged', {
composed: true,
bubbles: true,
cancelable: true,
detail: { count: this.count }
})
);
}
render() {
return html`
<input value=${this.count} @input=${this.updateCount} type="text" />
`;
}
}
和我的观点:
import { LitElement, html, customElement, property } from 'lit-element';
@customElement('my-view')
export class MyView extends LitElement {
@property({ type: Number }) count: number = 0;
render() {
return html`
<p>${this.count}</p>
`;
}
}
为了让count 属性从my-form 更改为my-view,我调度了事件侦听器,然后在my-app 使用它,然后在handleCountChange 我将count 值分配给MyView 导入除了将其作为组件导入之外,还可以作为一个类。
目前,这是可行的,但我觉得还有很长的路要走,尤其是当我有更多嵌套组件时。我想知道这样做是否有更好的方法。
是否有类似于Context API 的东西存在于react.js
我考虑过使用redux,但有人不推荐使用 litElemnt。
我正在考虑的一个想法是将事件发送到document 而不是当前组件,但也许这是一个不好的做法!您有什么建议,请告诉我?
【问题讨论】:
-
"有人不推荐它与 litElemnt" 您应该使用对您有意义的工具。 Redux 似乎是一种合理的方法。 PWA Starter Kit 使用 LitElement 构建并使用 Redux。
标签: typescript custom-component state-management lit-element lit-html