[英]How to send props from parent to child with LitElement
Can someone show me some simple example about sending props from parent class to child?有人可以告诉我一些关于从父母 class 向孩子发送道具的简单示例吗? What is the problem:
问题是什么:
parent component:父组件:
import { LitElement, html, css } from 'lit-element'; import './child.js'; class Parent extends LitElement { constructor() { super() this.message = "hello world" } render() { return html `<child-component message=${this.message}></child-component>` //how to get this props in child component? } } customElements.define('parent-component', Parent);
and child component:和子组件:
import { LitElement, html, css } from 'lit-element'; class Child extends LitElement {... render() { return html `<p>${message from parent, but how}</p>` //message props should go to constructor? to render method as argument? how? } } } customElements.define('child-component', Child);
ok, I found solution.好的,我找到了解决方案。 If I want to define properties in Parent class I have to add dot.
如果我想在父 class 中定义属性,我必须添加点。
Reference: https://lit-element.polymer-project.org/guide/properties
参考: https://lit-element.polymer-project.org/guide/properties
render() { return html `<child-component.message=${this.message}></child-component>` }
So now everything is working.所以现在一切正常。
And full example:和完整的例子:
parent component:父组件:
import { LitElement, html, css } from 'lit-element'; import './child.js'; class Parent extends LitElement { constructor() { super() this.message = "hello world" } render() { return html `<child-component.message=${this.message}></child-component>` } } customElements.define('parent-component', Parent);
child component:子组件:
import { LitElement, html, css } from 'lit-element'; class Child extends LitElement {... render() { return html `<p>${this.message}</p>` //this.message have "hello world" value now } } customElements.define('child-component', Child);
Make it much standard.让它变得很标准。
In your child component., set properties to listen to message.在您的子组件中,设置属性以收听消息。
import { LitElement, html, css } from 'lit-element'; class Child extends LitElement { static get properties(){ return{ message: { type: String, } } } constructor(){ super(); console.log(message); } render() { return html `<p>${this.message}</p>` //this.message have "hello world" value now } } customElements.define('child-component', Child);
In children to load property from parent component:在子组件中从父组件加载属性:
@property({type: Number}) propertyChild: number; constructor() { super(); this.propertyChild = (this.parentElement as TypeParent).propertyParent; }
In parent to update properties on children:在父级中更新子级的属性:
override updated(): void { this.childNodes.forEach(node=>{ const nodeType = node as TypeChildren; if(nodeType.property) { nodeType.propertyChild = this.propertyParent; } }) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.