在react中,我们可以使用PropTypes将特定的属性标记为必需属性。
requiredFunc: PropTypes.func.isRequired,Vue还支持所需的属性:
propC: {
type: String,
required: true
},如何在lit-element中做到这一点?它是如此有趣,一个框架声称它很好,但不支持像必需属性这样的简单东西。
发布于 2021-06-17 15:38:14
React和Vue组件使用各自的运行时在受控环境中执行。Web组件不能具有相同级别的已清理环境。渲染周期为React/Vue/Angular/等完美定义。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>另外,使用你的组件的每个框架都可以有自己的初始化属性的方式。在什么时候应该触发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的通用基类来泛化验证行为,或者使用自定义装饰器来管理属性验证。
我同意与React和Vue相比,LitElement可能会感到笨拙,但总的来说,它有太多的问题需要处理,而React根本不需要处理。它很容易变得复杂。
https://stackoverflow.com/questions/68008726
复制相似问题