【发布时间】:2023-03-10 14:57:01
【问题描述】:
我有一个包含 Stencil.js 的存储库,我创建了几个 Web 组件,它们嵌套并在 Stencil 开发环境中工作。例如,我有一个使用子组件的父组件:
import { Component, h, Prop, State } from "@stencil/core";
@Component({
tag: "parent-component"
})
export class MyParent {
@Prop() carddata: any;
render() {
return (
<div>
<child-component
carddata={this.carddata}
/>
</div>
);
}
}
这是子组件:
import { Component, Prop, h } from "@stencil/core";
@Component({
tag: "child-component"
})
export class MyChild {
@Prop() carddata: any;
renderItems(items: string[]): string {
let newString = "";
items.map((item: string) => {
newString = newString.concat(item, ", ");
});
return newString.substr(0, newString.length - 2);
}
render() {
const { items } = JSON.parse(this.carddata);
return (
<p>
Items: <b>{this.renderItems(items)}</b>
</p>
);
}
}
当我构建和使用在另一个存储库(React 应用程序)中创建的包时,我在渲染 Web 组件时出现错误。这是我使用 Web 组件的 React 组件:
[...]
import * as cardData from "./card-mock-data.json";
[...]
render() {
return (
<Wrap>
<parent-component
carddata={JSON.stringify(cardData)}/>
</Wrap>
);
}
[...]
错误是TypeError: Cannot read property 'map' of undefined。很难调试,因为是编译后的代码,但错误似乎是指这段(编译后的)代码:
ChildComponent.prototype.renderItems= function (items) {
var newString = "";
items.map(function (item) {
newString = newString.concat(item, ", ");
});
return newString.substr(0, newString.length - 2);
};
也许我错了,我可以只使用 React 中的父标签将数据传递给嵌套组件吗?也许我错过了一些“解析”步骤?
感谢您的帮助
编辑:添加cardData sn-p:
{
"id": "invito-biologia-blu",
"titolo": "Il nuovo invito alla biologia blu",
"img": "http://media.curtisinvitoblu.bedita.net/a1/40/curti_a140cb3359b7611d84f80e384d2fb49b/curtis_plus-1A_320x_71bc3567ace1ff728caef1b381d7535b.png",
"tags": ["Polimeri", "biochimica", "biotecnologie", "sostenibilità"],
"autori": ["Helena Curtis", "Sue Barnes", "Alicia Mastroianni"],
"anno": 2017,
"actions": ["Leggi sul browser", "Sito e risorse del libro", "ZTE"]
}
当我在 render() 中记录 cardData 时,我有这个:
Module {default: {…}, __esModule: true, Symbol(Symbol.toStringTag): "Module"}
【问题讨论】:
-
如果您登录 React 部分,cardData 实际上是什么样子的?
-
@AlexanderStaroselsky 这是一个 JSON 文件,我也用日志更新了问题
-
看起来 JSON 不像您期望的那样导入。根据日志,它似乎将其视为模块而不是 JSON。这可能是您的 webpack 配置的问题。下一个问题是我在您的 json 中没有看到名为 items 的属性。我提到这一点是因为在您的子模板组件中,您试图提取一个名为 items 的属性,该属性似乎不存在,因此出现未定义的错误。假设您传递实际的 JSON 数据,您可能不会解构项目,您只需将整个解析的有效负载传递给 renderItems。
-
你需要一个特定的加载器来使用 webpack 加载 json,但是你的导入在语法方面也可能是错误的。只需从'whatever.json'导入cardData
-
@AlexanderStaroselsky 谢谢,我设置了从 ts 文件导入,它可以工作
标签: javascript reactjs web-component custom-element stenciljs