您需要一些东西来将 JSX 转换为 JS 函数调用。 React 使用 Babel 来做到这一点——你可能也最好这样做。
Preact 的创建者提供了一个库,它基本上可以满足您的需求,称为 vhtml。标语是“将 JSX/Hyperscript 渲染为 HTML 字符串,无需 VDOM”。
这是撰写本文时自述文件的副本:
用法
// import the library:
import h from 'vhtml';
// tell babel to transpile JSX to h() calls:
/** @jsx h */
// now render JSX to an HTML string!
let items = ['one', 'two', 'three'];
document.body.innerHTML = (
<div class="foo">
<h1>Hi!</h1>
<p>Here is a list of {items.length} items:</p>
<ul>
{ items.map( item => (
<li>{ item }</li>
)) }
</ul>
</div>
);
新:“排序”组件!
vhtml 故意不将 JSX 转换为 Virtual DOM,而是将其直接序列化为 HTML。但是,仍然可以将基本的纯功能组件用作一种“模板部分”。
当 vhtml 被赋予一个 Function 作为 JSX 标记名称时,它将调用该函数并将其传递给 { children, ...props }。这与 react/preact 中的纯功能组件签名相同,除了 children 是一个已经序列化的 HTML 字符串数组。
这实际上意味着可以使用这些简单的组件甚至更高阶的组件来构建组合模板修饰符。
这是上一个示例的更复杂的版本,它使用组件来封装迭代项:
让 items = ['one', 'two'];
const Item = ({ item, index, children }) => (
<li id={index}>
<h4>{item}</h4>
{children}
</li>
);
console.log(
<div class="foo">
<h1>Hi!</h1>
<ul>
{ items.map( (item, index) => (
<Item {...{ item, index }}>
This is item {item}!
</Item>
)) }
</ul>
</div>
);
以上输出如下 HTML:
<div class="foo">
<h1>Hi!</h1>
<ul>
<li id="0">
<h4>one</h4>This is item one!
</li>
<li id="1">
<h4>two</h4>This is item two!
</li>
</ul>
</div>