Skip to content

TSX 简明语法

Kagol edited this page Feb 27, 2021 · 1 revision

简明语法

参考:

Vue 3 Babel JSX 插件

Vue3 JSX 使用指南

JSX 简介

嵌入表达式

使用大括号包裹,支持任何有效的 JavaScript 表达式,比如:2 + 2user.firstNameformatName(user)

const name = 'Vue DevUI'
const element = <h1>Hello, { name }</h1>

条件渲染

tsx本身也是一个条件表达式。

使用 if/else

const element = (name) => {
  if (name) {
    return <h1>Hello, { name }</h1>
  } else {
    return <h1>Hello, Stranger</h1>
  }
}

使用三目运算符

const element = icon ? <span class="icon"></span> : null;

列表渲染

const data = [{
  id: 1,
  title: '通用'
}, {
  id: 2,
  title: '导航'
}]

const element = data.map(item => {
  return <div>{ item.title }</div>
})

标签属性

const href = 'https://devui.design'

const element = <a href={href}></a>

类名 class

const element = <div className={`devui-accordion-item-title ${ disabled ? 'disabled' : '' }`}></div>

样式 style

const width = '100px'

const element = <button style={{ width: width, fontSize: '16px' }}></button>

注意:

  • class -> className
  • tabindex -> tabIndex

组件模板

button.tsx:

import { defineComponent } from 'vue'
import './button.scss';

type IButtonType = 'button' | 'submit' | 'reset';

export default defineComponent({
  name: 'd-button', // 组件名
  props: { // 输入/输出
    type: {
      type: String as () => IButtonType,
      default: 'button'
    },
    btnClick: {
      type: Function as unknown as () => ((event: MouseEvent) => void)
    }
  },
  setup(props, ctx) { // 模板和逻辑
    const { type, btnClick } = props;

    return () => {
      return <button
        type={type}
        onClick={btnClick}
      >{ ctx.slots.default?.() }</button>
    }
  }
})