如何在Qwik框架中将组件作为组件属性传递?
在Qwik中传递组件作为属性的实现方式
在Qwik中传递组件作为属性的逻辑和React类似,但需要使用Qwik提供的类型定义,具体实现如下:
步骤1:导入必要的类型与工具
首先从Qwik包中导入所需的类型和组件装饰器:
import { component$, Component, JSX } from '@builder.io/qwik';
步骤2:定义组件Props接口
使用Component类型声明可传递的组件属性,这对应React中的ComponentType:
interface ButtonProps { // 可选的图标组件,类型为Qwik组件,接收svg元素的原生属性 icon?: Component<JSX.IntrinsicElements['svg']>; children: JSX.Element; }
步骤3:实现接收组件属性的Button组件
通过解构props拿到传递的组件,渲染时遵循大写变量名的规则:
export const Button = component$(({ icon: Icon, children }: ButtonProps) => { return ( <button> {Icon && <Icon />} {children} </button> ); });
步骤4:定义要传递的Icon组件
实现一个普通的Qwik组件,这里以SVG图标为例:
export const DotIcon = component$((props: JSX.IntrinsicElements['svg']) => { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="24" height="24" {...props} > <circle cx="12" cy="12" r="5" /> </svg> ); });
步骤5:在父组件中使用传递组件属性的Button
直接将组件作为属性传入即可:
export default component$(() => { return <Button icon={DotIcon}>Example button</Button>; });
关键说明
PropFunction仅用于需要序列化的回调函数(如事件处理函数),传递组件不需要使用它,直接用Component类型声明即可。- 渲染传递的组件时,变量名必须大写(如
Icon),这是Qwik识别组件的规则,和React一致。
内容的提问来源于stack exchange,提问作者Petr Tripolsky
相关产品推荐
相关产品推荐

