定义
创建虚拟 DOM 节点 (vnode)。
类型
// 完整参数签名
function h(
type: string | Component, //可以创建原生dom,也可以创建组件
props?: object | null, // 可以给组件(原生dom)插入文字,添加事件等
children?: Children | Slot | Slots
): VNode;
// 省略 props
function h(type: string | Component, children?: Children | Slot): VNode;
type Children = string | number | boolean | VNode | null | Children[];
type Slot = () => Children;
type Slots = { [name: string]: Slot };
渲染原生dom
const box = document.createElement('div');
const container = document.querySelector('#test');
container.appendChild(box);
box.innerHTML = `<h3>渲染原生dom</h3>`;
render(
h('div', {
innerHTML: 'h函数666',
style: {
color: 'red',
},
class: 'test',
}),
box
);
渲染组件
const box = document.createElement('div');
const container = document.querySelector('#test');
container.appendChild(box);
box.innerHTML = `<h3>渲染ant的按钮组件</h3>`;
render(
h(AButton, {
innerHTML: '按钮',
onClick: () => {
alert('按钮点击了');
},
}),
box
);
h 函数中的 v-model
const switchValue = ref(false);
const hVModel = () => {
const box = document.createElement('div');
const container = document.querySelector('#test');
container.appendChild(box);
box.innerHTML = `<h3>v-model</h3>`;
render(
h(ASwitch, {
checked: switchValue,
['onUpdate:checked']: (checked) => {
switchValue.value = checked;
},
}),
box
);
};
使用场景(ant design 表格自定义渲染为例)
const columns: TableColumnsType = [
{
title: 'Name',
dataIndex: 'name',
},
// ...
{
title: 'Tag',
dataIndex: 'tag',
customRender: ({ record }) => {
const score = record['score'];
if (score >= 90) {
return h(ATag, { innerText: '优', color: '#108EE9' });
} else if (score >= 80 && score < 90) {
return h(ATag, { innerText: '良', color: '#2DB7F5' });
} else if (score < 80 && score >= 60) {
return h(ATag, { innerText: '中', color: '#87D068' });
} else {
return h(ATag, { innerText: '差', color: '#FF5500' });
}
},
},
];