【发布时间】:2021-11-09 01:46:12
【问题描述】:
目前我需要让 Preact 应用程序在没有任何构建工具的情况下工作,只需使用带有 import 语句的 index.html 从 CDN 获取 preact。我可以从 CDN 导入 'useState' 钩子没有问题,甚至可以 console.log() 函数 useState 的值,但是每当我尝试使用它时,我都会收到一条错误消息:
'Uncaught TypeError: u is undefined'
你会碰巧知道为什么会这样吗?我尝试在功能组件内部和外部使用 useState 函数,但无论哪种方式都不起作用。我在这里错过了什么吗?谁能帮我指出正确的方向?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
import { h, Component, render } from 'https://unpkg.com/preact?module';
import { useState } from 'https://unpkg.com/preact@latest/hooks/dist/hooks.module.js?module'
import htm from 'https://unpkg.com/htm?module';
// Initialize htm with Preact
const html = htm.bind(h);
const App = (props) => {
const [testVar, setTestVar] = useState(0);
var countVariable = 0;
const incrementButtonHandler = () => {
countVariable = countVariable + 1;
}
const logMethod = () => {
console.log(countVariable);
countVariable = countVariable + 1;
}
return html`<div>
<h1>Test ${props.name}!: ${countVariable}</h1>
<button onClick=${logMethod}>Increment</button>
</div>`;
}
render(html`<${App} name="World" />`, document.body);
</script>
</head>
<body>
</body>
</html>
【问题讨论】:
标签: javascript preact