如何解决如何在 lit-element 中声明必需的属性
在 React 中,我们可以使用 PropTypes
将特定的 prop 标记为必需的。
requiredFunc: PropTypes.func.isrequired,
Vue 还支持所需的道具:
propC: {
type: String,required: true
},
如何在 lit-element 中做到这一点?一个框架声称它非常好,但不支持诸如必需属性之类的简单事情,这真是太有趣了。
解决方法
React 和 Vue 组件使用各自的运行时在受控环境中执行。 Web 组件不能具有相同级别的净化环境。为 React/Vue/Angular/etc 完美定义了渲染周期。可以通过多种方式初始化 Web 组件:
// Using custom registered tag
const myComp = document.createElement('my-custom');
// Using constructor
const myComp = new MyCustom();
// Initialization using plain html
<div>
<my-comp>
</div>
所以,生命周期不容易不可控。让我们假设您有一个带有 prop - myRequiredProp
的 Web 组件。并且,它被初始化为:
// Pass prop at the time of initialization
const myComp1 = new MyCustom({ myRequiredProp: 10 });
// Pass prop at a later time.
const myComp2 = new MyCustom();
// ... after some time
myComp2.myRequiredProp = 10;
// And how to pass props if component is being used directly in HTML.
// Is this right way? What if `my-required-prop` should be object and not a primitive like number or string?
<div>
<my-comp my-required-prop="10" />
</div>
另外,每个使用你的组件的框架都可以有自己的初始化 props 的方式。应该在什么时候触发 prop 的验证。如果组件刚刚初始化并且从未呈现怎么办。在 Web 组件的情况下,要针对每种情况做出这些决定并不容易。因此,最好将这种关注放在核心之外。 lit-element
有意避免此类开放式决定。
话虽如此,您可以为道具构建自己的验证系统。您可以控制道具验证何时发生。例如,您可以在 render
时间验证道具。
export class MyElement extends LitElement {
@property({})
count = 0;
@property()
name = 'World';
validateAllProps() {
// Your validation logic.
// Use joi or zod to validation `this`.
return true;
}
render() {
// Trigger validation here
if (!this.validateAllProps) {
console.warn('Invalid props');
}
return html`
<h1>Hello,${this.name}!</h1>
<button @click=${this._onClick}>
Click Count: ${this.count}
</button>
`;
}
}
或者您也可以使用自定义 setter 或使用转换器函数验证道具。
export class MyElement extends LitElement {
#name = 'World';
set name(name) {
if (typeof name !== 'string') {
console.warn('Invalid prop name for MyElement');
}
this.#name = name;
}
render() {
return html`
<h1>Hello,${this.name}!</h1>
`;
}
}
您应该能够使用扩展 LitElement 的公共基类或使用自定义装饰器来管理属性验证来概括验证行为。
我同意 LitElement
与 React 和 Vue 相比可能会感到尴尬,但总的来说,它有太多的问题需要处理,而 React 根本不需要处理。它很容易变得复杂。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。