vue tsx怎么给props设置默认值?

这样写报错:Uncaught TypeError: Cannot destructure property 'slots' of 'object null' as it is null.

import type { SetupContext } from "vue"

interface Props {

shadow?: boolean

}

export default function button (props: Props = { shadow: false }, { slots }: SetupContext) {

return (

<div class={["card", {shadow: props.shadow}]}>

{slots.default?.()}

</div>

)

}


回答:

调试了一下代码,vue 相关源码如下:

result = normalizeVNode(render.length > 1

? render(props, (process.env.NODE_ENV !== 'production')

? {

get attrs() {

markAttrsAccessed();

return attrs;

},

slots,

emit

}

: { attrs, slots, emit })

: render(props, null /* we know it doesn't need it */));

render 就是定义的函数组件,如果改函数有默认参数,那么函数的 length 就为 0, 就会执行
render(props, null /* we know it doesn't need it */)); 导致 SetupContext 为空,这个算 vue 的一个 bug, 解决办法就是不使用函数的默认值 ,代码如下:

import type { SetupContext } from "vue"

interface Props {

shadow?: boolean

}

export default function button (props: Props, { slots }: SetupContext) {

const shadow = props.shadow === undefined ? false: props.shadow

return (

<div class={["card", {shadow: props.shadow}]}>

{slots.default?.()}

</div>

)

}

补充说明一下: 函数式组件的 props 就算没有值也会传递一个空对象, 所以通过一个 函数参数默认值传递默认值是行不通的。


回答:

找了很久找到了

import * as React from 'react';

export interface Props {

name: string;

enthusiasmLevel?: number;

}

function Hello({ name, enthusiasmLevel = 1 }: Props) {

if (enthusiasmLevel <= 0) {

throw new Error('You could be a little more enthusiastic. :D');

}

return (

<div className="hello">

<div className="greeting">

Hello {name + getExclamationMarks(enthusiasmLevel)}

</div>

</div>

);

}

export default Hello;

以上是 vue tsx怎么给props设置默认值? 的全部内容, 来源链接: utcz.com/p/932792.html

回到顶部