1. 从父组件向子组件传递数据
- 方法:通过属性(props)传递。在父组件中,将数据作为属性传递给子组件,子组件通过定义相应的属性来接收数据。
- 示例:
- 假设我们有一个
Parent
组件和一个 Child
组件。
- 在
Parent.qwik
中:
import { component$, useSignal } from '@builder.io/qwik';
import Child from './Child.qwik';
export default component$(() => {
const message = useSignal('Hello from parent');
return (
<div>
<Child text={message.value} />
</div>
);
});
import { component$, Props } from '@builder.io/qwik';
export interface ChildProps extends Props {
text: string;
}
export default component$(({ text }: ChildProps) => {
return <p>{text}</p>;
});
2. 从子组件向父组件传递数据
- 方法:通常通过回调函数实现。父组件将一个函数作为属性传递给子组件,子组件在需要时调用该函数,并将数据作为参数传递给父组件。
- 示例:
import { component$, useSignal } from '@builder.io/qwik';
import Child from './Child.qwik';
export default component$(() => {
const receivedMessage = useSignal('');
const handleChildMessage = (message: string) => {
receivedMessage.value = message;
};
return (
<div>
<Child onMessage={handleChildMessage} />
<p>{receivedMessage.value}</p>
</div>
);
});
import { component$, Props } from '@builder.io/qwik';
export interface ChildProps extends Props {
onMessage: (message: string) => void;
}
export default component$(({ onMessage }: ChildProps) => {
const sendMessage = () => {
onMessage('Hello from child');
};
return <button onClick={sendMessage}>Send message to parent</button>;
});
3. 双向数据绑定(父子组件间较紧密的交互)
- 方法:在Qwik中,可以通过
useSync
等方式来实现双向绑定。本质上还是结合属性传递和回调函数。
- 示例:
import { component$, useSignal } from '@builder.io/qwik';
import Child from './Child.qwik';
export default component$(() => {
const value = useSignal('Initial value');
const handleValueChange = (newValue: string) => {
value.value = newValue;
};
return (
<div>
<Child value={value.value} onChange={handleValueChange} />
<p>{value.value}</p>
</div>
);
});
import { component$, Props } from '@builder.io/qwik';
export interface ChildProps extends Props {
value: string;
onChange: (newValue: string) => void;
}
export default component$(({ value, onChange }: ChildProps) => {
const handleInputChange = (e: any) => {
onChange(e.target.value);
};
return <input type="text" value={value} onChange={handleInputChange} />;
});