MST

星途 面试题库

面试题:Qwik 组件中如何有效结合 Props 与状态管理实现数据传递与更新

在一个 Qwik 项目中,有一个父组件和一个子组件。父组件有一个状态变量 `count`,需要传递给子组件并在子组件中展示,同时子组件有一个按钮,点击按钮要能增加父组件的 `count` 值。请描述实现这个功能的具体步骤,并给出关键代码示例。
50.3万 热度难度
前端开发Qwik

知识考点

AI 面试

面试题答案

一键面试
  1. 实现步骤
    • 在父组件中定义 count 状态变量及修改 count 的函数。
    • count 和修改 count 的函数作为属性传递给子组件。
    • 在子组件中接收并展示 count,并为按钮添加点击事件调用传递过来的修改 count 的函数。
  2. 关键代码示例
    • 父组件代码(假设为 ParentComponent.tsx
import { component$, useState } from '@builder.io/qwik';
import ChildComponent from './ChildComponent';

export default component$(() => {
    const [count, setCount] = useState(0);

    const incrementCount = () => {
        setCount(count + 1);
    };

    return (
        <div>
            <ChildComponent count={count} increment={incrementCount} />
        </div>
    );
});
- **子组件代码(假设为 `ChildComponent.tsx`)**:
import { component$ } from '@builder.io/qwik';

export interface ChildProps {
    count: number;
    increment: () => void;
}

export default component$((props: ChildProps) => {
    return (
        <div>
            <p>Count: {props.count}</p>
            <button onClick={props.increment}>Increment Count</button>
        </div>
    );
});