JSX基本语法&使用


JSX文档:https://zh-hans.reactjs.org/docs/introducing-jsx.html

PS:我只记录了一些注意点,前置的使用示例&语法未在本篇笔记中。

1. jsx使用配置

  • babel配置

    • 安装Bable支持的 Vue的jsx插件

      npm install @vue/bable-plugin-jsx -D
      
  • bable.config.js配置文件中配置插件

    0

  • jsx中赋值变量时要使用大括号:{}

    image-20230212192626262

  • 插槽的使用

    • 双括号代表:外层代表函数;里层的代表是对象形式。
  • image-20230212192940925

  • 优势

    • 可以在里面任意写JS的代码👆🏻。
  • 使用场景

    • 封装组件库时可以使用。

2. 语法&注意点

  1. 元素属性名使用驼峰命名法: (例👇🏻marginLeft属性)

    const renderDom = (
      <>
        <n-button onClick={handleEditIncluded.bind(this, record, '')}>{text}</n-button>
        <n-button
          v-show={record.join_status === 1}
          onClick={handleEditIncluded.bind(this, record, 'editRoleBtn')}
          style={{ marginLeft: '5px' }}
        >
          更改入驻GS
        </n-button>
      </>
    );
    
  2. 变量使用{ }包裹。

  3. 添加样式时:class用className替换(因为class在JS中是关键字)。

2.1 常用指令在JSX的写法

  • template常用指令:v-if、v-for、v-modal等指令在JSX无法使用。所以要注意一下写法:

    • innerHTML =》domProps

    • v-if =》三目运算符或if判断

    • v-for =》maps

    • v-modal =》vue-cli4默认集成了 JSX 对 v-model 的支持,老项目可以安装插件babel-plugin-jsx-v-model

    • 监听事件(click、change) =》用bind或箭头函数传参

    • 事件修饰符:

      • .stop阻止事件冒泡 =》event.stopPropagation()
      • .prevent阻止默认行为 =》event.preventDefault()
      • .self当事件从侦听器绑定的元素本身触发时才触发回调 =》使用条件判断
    • 更多:https://juejin.cn/post/7018742119082754062#heading-3

一些示例:

// v-html或v-text:
render() {
    const { htmlCode } = this
    return (
        <div>
            <div domPropsInnerHTML={htmlCode}></div>
        </div>
    );
   }


// 点击事件:
methods: {
    handleClick(val){
        alert(val)
    }
  },
<button type="button" onClick={this.handleClick.bind(this, 11)}>点击bind</button>
<button type="button" onClick={() => this.handleClick(11)}>点击箭头函数</button>

文章作者: polariis
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 polariis !
评论
  目录