我想传递一个对象数组,然后遍历该数组并渲染每个对象。
我有以下 html 文件:
<stencil-component
cards = '[{"cardTitle"="placeholder", "copy"="copy1"},{"cardTitle"="placeholder2", "copy"="copy3"}]'>
</stencil-component>
在我的 tsx 文件中有以下内容:
@Prop() cards: Array<object> = [];
render(){
return (
{this.cards.map(card) => {
return (
<div>
<h1>{card.cardTitle}</h1>
<p>{card.copy}</p>
</div>
);
})}
)
}
我什至无法显示数组。我尝试使用 JSON.parse 函数来解析数据,但也没有用。如果有人可以提供帮助,我将不胜感激!
最佳答案
HTML 属性只能保存字符串,因此如果您在 Stencil 之外使用该组件,则必须将所有属性作为字符串传递。
在 Stencil(可能还有一些框架)中,您可以像这样传递它:
<stencil-component
cards={[{"cardTitle":"placeholder", "copy":"copy1"},{"cardTitle":"placeholder2", "copy":"copy3"}]}>
</stencil-component>
注意:您的 JSON 不正确,您需要将 =
替换为 :
。
如果您需要在纯 HTML 中使用该组件,您将不得不手动解析 属性字符串或使用 javascript 设置它。
有examples of this in the docs :
Setting the prop manually
import { Prop } from '@stencil/core'; export class TodoList { @Prop() myObject: object; @Prop() myArray: Array<string>; }
HTML
<todo-list></todo-list> <script> const todoListElement = document.querySelector('todo-list'); todoListElement.myObject = {}; todoListElement.myArray = []; </script>
Watching props changes
import { Prop, State, Watch } from '@stencil/core'; export class TodoList { @Prop() myObject: string; @Prop() myArray: string; @State() myInnerObject: object; @State() myInnerArray: Array<string>; componentWillLoad() { this.parseMyObjectProp(this.myObject); this.parseMyArrayProp(this.myArray); } @Watch('myObject') parseMyObjectProp(newValue: string) { if (newValue) this.myInnerObject = JSON.parse(newValue); } @Watch('myArray') parseMyArrayProp(newValue: string) { if (newValue) this.myInnerArray = JSON.parse(newValue); } }
HTML
<todo-list my-object="{}" my-array="[]"></todo-list>
关于typescript - 对象数组 Prop 装饰器 StencilJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58697857/