- 实现步骤:
- 在父组件中定义
count
状态变量及修改 count
的函数。
- 将
count
和修改 count
的函数作为属性传递给子组件。
- 在子组件中接收并展示
count
,并为按钮添加点击事件调用传递过来的修改 count
的函数。
- 关键代码示例:
- 父组件代码(假设为
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>
);
});