javascript - 如何在 Preact 和没有构建工具的情况下使用 useState 钩子?
问题描述
目前,我需要让 Preact 应用程序在没有任何构建工具的情况下工作,只需使用带有 import 语句的 index.html 从 CDN 获取 preact。我可以从 CDN 导入 'useState' 钩子没有问题,甚至可以 console.log() 函数 useState 的值,但是每当我尝试使用它时,我都会收到一条错误消息:
你会碰巧知道为什么会这样吗?我尝试在功能组件内部和外部使用 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>
解决方案
这是 unpkg 可以做的已知错误和限制,请参阅:https ://github.com/preactjs/preact/issues/2571
不过有几个简单的修复方法:
- 为每个模块使用已解析的 URL(注意
@latest
preact 导入中的)
import { h, render } from 'https://unpkg.com/preact@latest?module'
import { useState } from 'https://unpkg.com/preact@latest/hooks/dist/hooks.module.js?module'
import { html } from 'https://unpkg.com/htm/preact/index.module.js?module'
- 使用没有此问题的 CDN 可以正确解析模块,例如skypack:
import { h, render } from 'https://cdn.skypack.dev/preact';
import { useState } from 'https://cdn.skypack.dev/preact/hooks';
import { html } from 'https://cdn.skypack.dev/htm/preact';
要么应该工作。
推荐阅读
- java - 如何使用链接包从一维数组中删除重复项?
- java - 使用 Atom 创建 Java 环境变量
- r - 根据该列中的滞后值改变一个新列 - dplyr 方法
- java - 使用 Serenity BDD 剧本管理 React DOM
- reactjs - 将 React Redux 与路由器集成时出现问题?
- scala - Flink Core 和 Flink CEP 在能力方面有什么区别?
- javascript - 如何在 JavaScript 中将二维数组中的相邻单元格随机组合在一起?
- javascript - 表单邮件程序正在工作,但现在没有
- python - 列表对象的python变量名,最佳实践
- r - R:按数据集分组,条件是组中特定列中的所有值都符合某些要求