笔记-第二十七章-函数式组件 h函数(自用)

116 阅读1分钟

函数式组件 h函数

<template>模板是需要进行编译的,通过parser函数转成ast抽象语法树然后再通过transform转成一个js API再通过generate生成一个render函数。

<template>
    <div><span>1</span></div>
</template>

编译后:

let render = () => {
    return h('div', {}, [
        h('span', {}, '1')
    ])
}

h函数可以跳过这些编译流程,直接到render函数这步。

语法

h(tagName|component, object|null, string|tag|number|boolean|null|Children[])
  • 第一个参数是标签或者是组件
  • 第二个参数是该标签或者组件的属性,属性中包含了事件,注意事件是带on的(onClick)。
  • 第三个参数是该标签或组件的内容,内容可以是文本也可以是子元素。

示例:

  • 创建元素
    let button = () => {
        return h('button', 
                 { class: 'btn',
                   onClick: () => { console.log('点击了') }
                 },
                 '点击我')
    }
    
  • 使用
    <template>
        <div>
            <Btn />
        </div>
    </template>
    

动态的修改属性

比如需要动态的切换h函数生成的元素的类,通过按钮的type切换元素的类:

  • 模板:

        <template>
            <div>
                <Btn type="success" />
                <Btn type="error" />
            </div>
        </template>
    
  • js:

    interface Props {
        type: 'success'|'error'
    }
    
    let button = (props: Props) => {
            return h('button', 
                     { 
                       class: props.type === 'success' ? 'green' : 'red',
                       onClick: () => { console.log('点击了') }
                     },
                     '点击我')
        }
    
  • style:

    .green {
        color: green;
        border: green;
    }
    .red {
        color: red;
        border: red;
    }
    

    效果:

    image.png

读取插槽

  • 模板:

        <template>
            <div>
                <Btn type="success">123123</Btn>
            </div>
        </template>
    
  • js:

    interface Props {
        type: 'success'|'error'
    }
    
    let button = (props: Props, ctx) => {
            return h('button', 
                     { 
                       class: props.type === 'success' ? 'green' : 'red',
                       onClick: () => { console.log('点击了') }
                     },
                     ctx.slots.default())
        }
    

    效果:

    image.png

h()函数式组件一般用来封装小组件,比如ButtonMessageBox等等。