javascript - stenciljs 手表装饰器不触发
问题描述
我正在尝试将 JSON 字符串传递给我的组件道具,并让组件将字符串解析为 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}
);
}
}
索引.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
生命周期钩子中调用它:
componentWillLoad() {
this.watchHandler(this.newValue);
}
推荐阅读
- javascript - 无法将复选框设置为选中 - 与 DOM 加载相关,
- css - VueJS:禁用任何全局 CSS,只允许组件中的范围 CSS
- c++ - 将整数解释为字节数组的安全性
- f# - Excel Dna / F#中的多态性
- java - 在布局中动态插入图像
- c# - Bittrex websocket 编码
- java - viewpager 错误的项目位置 pageradapter
- python - 网络爬虫不跟随链接
- php - Laravel:将变量传递给视图并将其作为函数中的全局变量访问
- javascript - 我需要比较两个字符串(或数组)并返回它们的相似度百分比,无论它们的顺序如何