具有TypeScript和JSX的Vue功能组件

时间:2020-05-07 09:58:31

标签: typescript vue.js jsx vue-class-components vue-functional-component

我有2个组成部分。第一个看起来像这样:

import { RenderContext, VNode } from 'vue';

import './BaseTitle.sass';

export interface IBaseTitleProps {
  level: number;
}

export const BaseTitle = (context: RenderContext<IBaseTitleProps>): VNode => {
  const { level } = context.props;
  const HeadingComponent = `h${level}`;
  return (
    <HeadingComponent
      class={`title base-title base-title_level-${level} ${context.data.staticClass || ''} ${context.data.class ||
        ''}`}>
      {context.children}
    </HeadingComponent>
  );
};

第二个:

import { VueComponent } from 'types/vue-components';
import { Component } from 'nuxt-property-decorator';
import { VNode } from 'vue';
import { BaseTitle } from 'components/base/BaseTitle';

@Component({
  name: 'TheHeader',
})
export default class TheHeader extends VueComponent {
  public render(): VNode {
    return (
      <header class='page-header'>
        <BaseTitle level={4}>Page title</BaseTitle>
      </header>
    );
  }
}

在那里传递道具level时出现错误。

TS2322: Type '{ level: number; }' is not assignable to type 'RenderContext<IBaseTitleProps>'.   Property 'level' does not exist on type 'RenderContext<IBaseTitleProps>'.

RenderContext界面。

export interface RenderContext<Props=DefaultProps> {
  props: Props;
  children: VNode[];
  slots(): any;
  data: VNodeData;
  parent: Vue;
  listeners: { [key: string]: Function | Function[] };
  scopedSlots: { [key: string]: NormalizedScopedSlot };
  injections: any
}

我可以将其重写为类似的内容

<BaseTitle
    props={{
     level: 4,
    }}
 />

但这还要求我从RenderContext界面传递所有其他字段

如何正确使用功能组件和TypeScript?有什么例子吗?谢谢。

0 个答案:

没有答案