首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vue TSX -如何告诉Typescript允许在可重用组件中使用HTML属性?

Vue TSX -如何告诉Typescript允许在可重用组件中使用HTML属性?
EN

Stack Overflow用户
提问于 2021-03-18 12:07:03
回答 1查看 402关注 0票数 5

假设我有这样的输入组件:

代码语言:javascript
复制
import { defineComponent } from "@vue/runtime-core"

export default defineComponent({
    inheritAttrs: false,
    setup(props, { attrs }) {
        return () => (
            <div>
                <input type="text" {...attrs} />
            </div>
        )
    }
})

现在,我像这样使用这个组件并提供type="password"属性:

代码语言:javascript
复制
import { defineComponent } from "@vue/runtime-core"
import Input from "./components/input"

export default defineComponent({
    setup(props, { attrs }) {
        return () => <Input type="password"></Input>
    }
})

但是Typescript抱怨道:

代码语言:javascript
复制
Property 'type' does not exist on type 'IntrinsicAttribute'> & VNodeProps & AllowedComponentProps & ComponentCustomProps>'
EN

回答 1

Stack Overflow用户

发布于 2021-03-20 19:22:22

因此,我不是Vue.JS专家(请告诉我它是否不起作用以及原因),但经过一些研究后,我发现必须通过将props对象添加到defineComponent来键入props。这将告诉TypeScript您可以传递特定的道具。

代码语言:javascript
复制
import { defineComponent } from "@vue/runtime-core"

export default defineComponent({
    inheritAttrs: false,
    props: {
        type: String // this is the typing (warning: you cannot use typescript types here)
    }
    setup(props, { attrs }) {
        return () => (
            <div>
                <input type={props.type ?? "text"} {...attrs} />
            </div>
        )
    }
})

您可能会问??操作符是做什么的。我喜欢称它为“默认运算符”,因为它将其前面的值默认为它之前的值,以及它后面的值。在本例中,这意味着如果props.typeundefinednull,它将用"text"替换它。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66684622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档