gpt4 book ai didi

preact - import { h } from preact - 什么时候需要

转载 作者:行者123 更新时间:2023-12-04 06:53:02 24 4
gpt4 key购买 nike

我目前正在使用 CLI 构建 Preact PWA。

我的理解是,无论我在哪里使用 JSX 定义了组件,我都需要 import { h } from 'preact'在文件的顶部。

我删除了该导入语句的所有实例,但应用程序仍然运行并构建得非常好。

有人可以让我直接在这里,因为我现在有点困惑 - 也许幕后某处有一些魔法?

最佳答案

当你写一个像这样的 jsx 语法时

render() {
return <div id="abc">Hello World</div>
}

在屏幕后面,它将被转换为
render() {
return h('div', { id: 'abc' }, 'Hello World')
}

所以,什么时候需要导入 h ?

答案是 每次使用 jsx 语法时 . JSX 不是 JavaScript 规范的一部分,它必须转换为等效的函数调用。其中在 preact 中使用 h或使用 React.createElement 进行 react .

正如你提到的,我们可以制作 import自动使用附加 babel-plugin-jsx-pragmatic插入。
module.exports = {
presets: [],
'plugins': [
['@babel/plugin-transform-react-jsx', { pragma: 'h' }],
['babel-plugin-jsx-pragmatic', {
module: 'preact',
import: 'h',
export: 'h',
}],
],
}

了解更多信息: https://github.com/jmm/babel-plugin-jsx-pragmatic

关于preact - import { h } from preact - 什么时候需要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52417272/

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