MST

星途 面试题库

面试题:Qwik组件化开发中如何实现父子组件通信

在Qwik的组件化开发里,通常会涉及到父子组件之间的数据传递和交互。请描述一下实现父子组件通信的常用方法,并举例说明如何在Qwik项目中具体实现。
48.7万 热度难度
前端开发Qwik

知识考点

AI 面试

面试题答案

一键面试

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>
  );
});
  • Child.qwik 中:
import { component$, Props } from '@builder.io/qwik';

export interface ChildProps extends Props {
  text: string;
}

export default component$(({ text }: ChildProps) => {
  return <p>{text}</p>;
});

2. 从子组件向父组件传递数据

  • 方法:通常通过回调函数实现。父组件将一个函数作为属性传递给子组件,子组件在需要时调用该函数,并将数据作为参数传递给父组件。
  • 示例
    • Parent.qwik 中:
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>
  );
});
  • Child.qwik 中:
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 等方式来实现双向绑定。本质上还是结合属性传递和回调函数。
  • 示例
    • Parent.qwik 中:
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>
  );
});
  • Child.qwik 中:
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} />;
});