Ant-design-vue: table 组件columns选项在组件外部定义时,customRender中使用jsx报错

Created on 12 Sep 2019  ·  9Comments  ·  Source: vueComponent/ant-design-vue

  • [ ] I have searched the issues of this repository and believe that this is not a duplicate.

Version

undefined

Environment

vue:2.6.10 chrome :76

Reproduction link

Edit on CodeSandbox

Steps to reproduce

使用table组件,组件外部定义columns

What is expected?

jsx正常运行

What is actually happening?

报错:h is not defined

Most helpful comment

对象外不存在 Vue 生命周期的 this 和 this.$createElement ,如果是直接在对象内写,Vue 的编译器会自动为其加上 h 的定义,否则 请自己想办法把 h 注入进去

All 9 comments

对象外不存在 Vue 生命周期的 this 和 this.$createElement ,如果是直接在对象内写,Vue 的编译器会自动为其加上 h 的定义,否则 请自己想办法把 h 注入进去

// h 被隐式调用,定义时不可省略或更名
const generateColumns = function (h) {
     return [{ title: "inject",  customRender: val => ({ children: <a>{val}</a> }), }]
}

export default {
     data() {
         return {
             columns: []
         }
     },
     mounted() {
         this.columns = generateColumns(this.$createElement);
    }
}

@tangjinzhou 有考虑在 customRender 中自动注入 h 吗?这样就省去了使用 JSX 的麻烦。
我可以提个PR

文档上没说明傻乎乎在那排查了一个早上,后来才发现必须定义在data里面。。。。。。为什么不自动注入,想内置一些自定义渲染模版都不行

可以这样写

// config.js
const h = new Vue().$createElement
export default [
  {
     title: '状态',
     dataIndex: 'status',
     customRender: status => (
       <a-tag color={status === 1 ? 'blue' : 'red'} style='margin:auto;'>
         {status === 1 ? '已发布' : '未发布'}
      </a-tag>
     )
  }
]

官方的pro体验版里没有写h,为什么不报错呢?好奇怪?求助!

// const.js
export const columns = cxt => {
  /* eslint-disable-next-line */
  const h = cxt.$createElement
  return [
    {
      title: 'name',
      dataIndex: 'name',
      customRender: (text) => {
        return <span>{text}</span>
      }
    },
    ...
  ]
}
// list.vue
import { columns } from './const'

computed: {
  columns () {
    return columns(this)
  }
}

使用computed 返回column对象就好,会内置h

我是直接将 columns 初始化定值在data() 里面的,也会自动内置h()函数吧。这么操作我是可以使用的,不需要额外的设定 const h = this.$createElement()

Was this page helpful?
0 / 5 - 0 ratings