typescript - 对象数组 Prop 装饰器 StencilJS

标签 typescript stenciljs

我想传递一个对象数组,然后遍历该数组并渲染每个对象。

我有以下 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/

相关文章:

javascript - TS1148 ~ 如何使用 --module : "import" and typescript 2. x "none"

javascript - 如果一个函数组件具有内部可变状态,它可以被认为是纯函数组件吗?

javascript - 使用 webpack 捆绑模板组件

typescript - @types/jest index.d.ts 文件返回错误

javascript - Typescript 方法装饰器

generics - TypeScript 报告泛型函数中不存在的属性

javascript - 当我尝试在 Typescript 中应用过滤器时出错

javascript - 嵌套 Web 组件并将其与常规 HTML 混合

javascript - 在模板 Web 组件中实现框架