gpt4 book ai didi

javascript - stenciljs 观察装饰器未触发

转载 作者:行者123 更新时间:2023-11-28 13:00:35 27 4
gpt4 key购买 nike

我正在尝试将 JSON 字符串传递给我的组件 prop,并让组件将该字符串解析为 javascript 对象。

不幸的是@Watch装饰器没有触发...我做错了什么?我遵循了这个文档:https://stenciljs.com/docs/reactive-data#watch-decorator

以下是我的代码的相关部分:

ptw-input.tsx

    import { Component, Prop, Watch } from "@stencil/core";

@Component({
tag: "ptw-input",
styleUrl: "ptw-input.css",
shadow: true
})
export class PtwInput {

@Prop() data: string;

innerData: any;

@Watch('data')
watchHandler(newValue: string): void {
this.innerData = JSON.parse(newValue);
console.log('this.innerData', this.innerData);
}

render(): JSX.Element {
return (
<input type="text"
placeholder={this.innerData.placeholder}
disabled={this.innerData.disabled}
maxlength={this.innerData.maxlength}
);
}
}

index.html

    <head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0">
<title>Stencil Component Starter</title>
<script src="/build/ptw.js"></script>
</head>

<body>
<ptw-input data='{"placeholder":"Type something", "disabled":false, "maxlength":4}'></ptw-input>
</body>
</html>

...这是我的package.json

    {
"name": "ptw-input",
"version": "0.0.1",
"description": "PTW input component",
"module": "dist/esm/index.js",
"main": "dist/index.js",
"types": "dist/types/components.d.ts",
"collection": "dist/collection/collection-manifest.json",
"files": [
"dist/"
],
"scripts": {
"build": "stencil build",
"dev": "sd concurrent \"stencil build --dev --watch\" \"stencil-dev-server\" ",
"serve": "stencil-dev-server",
"start": "npm run dev",
"test": "jest",
"test.watch": "jest --watch"
},
"dependencies": {},
"devDependencies": {
"@stencil/core": "^0.9.11",
"@stencil/dev-server": "latest",
"@stencil/utils": "latest",
"@types/jest": "^21.1.1",
"jest": "^21.2.1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/ionic-team/stencil-component-starter.git"
},
"author": "Ionic Team",
"license": "MIT",
"bugs": {
"url": "https://github.com/ionic-team/stencil"
},
"homepage": "https://github.com/ionic-team/stencil",
"jest": {
"transform": {
"^.+\\.(ts|tsx)$": "<rootDir>/node_modules/@stencil/core/testing/jest.preprocessor.js"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(tsx?|jsx?)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"json",
"jsx"
]
}
}

我正在使用最新的 stenciljs,如 package.json 中所示,但控制台日志中除了以下错误之外没有任何内容:TypeError: Cannot read property 'placeholder' of undefined

最佳答案

当组件最初加载时,@Watch 装饰器不会触发。

要让该方法在组件加载时运行,请在 componentWillLoad 内调用它 lifecycle hook :

componentWillLoad() {
this.watchHandler(this.newValue);
}

关于javascript - stenciljs 观察装饰器未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50985239/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com