面试题答案
一键面试组件结构划分
- 单一职责原则:每个组件应只负责一项特定功能。比如在一个电商应用中,创建一个
ProductCard
组件专门负责展示单个商品的信息,包括图片、名称、价格等,而不是将购物车操作等无关功能也放入其中。这样使得组件功能明确,易于理解和维护。 - 模块化:将组件按照功能模块进行划分。例如,对于一个博客系统,可以分为
Post
组件用于展示文章内容,Comment
组件用于显示评论,以及Sidebar
组件展示侧边栏相关信息。每个模块相互独立又协同工作,提高代码的可复用性和可维护性。
数据传递
- 属性(Props)传递:父组件通过属性将数据传递给子组件。例如,在
ProductCard
组件中,父组件可能传递商品的name
、price
、imageUrl
等属性,子组件接收并展示这些数据。在 Qwik 中代码如下:// 父组件 import { component$, useStore } from '@builder.io/qwik'; import ProductCard from './ProductCard'; const ParentComponent = component$(() => { const product = useStore({ name: 'Sample Product', price: 19.99, imageUrl: 'https://example.com/image.jpg' }); return <ProductCard product={product} />; }); export default ParentComponent; // 子组件 ProductCard import { component$ } from '@builder.io/qwik'; const ProductCard = component$(({ product }) => { return ( <div> <img src={product.imageUrl} alt={product.name} /> <h2>{product.name}</h2> <p>Price: ${product.price}</p> </div> ); }); export default ProductCard;
- 事件回调:子组件通过触发事件,将数据传递回父组件。例如,在
ProductCard
组件中有一个 “添加到购物车” 按钮,当点击按钮时,需要通知父组件。代码如下:// 父组件 import { component$, useStore } from '@builder.io/qwik'; import ProductCard from './ProductCard'; const ParentComponent = component$(() => { const cart = useStore([]); const addToCart = (product) => { cart.push(product); }; const product = useStore({ name: 'Sample Product', price: 19.99, imageUrl: 'https://example.com/image.jpg' }); return <ProductCard product={product} onAddToCart={addToCart} />; }); export default ParentComponent; // 子组件 ProductCard import { component$ } from '@builder.io/qwik'; const ProductCard = component$(({ product, onAddToCart }) => { const handleClick = () => { onAddToCart(product); }; return ( <div> <img src={product.imageUrl} alt={product.name} /> <h2>{product.name}</h2> <p>Price: ${product.price}</p> <button onClick={handleClick}>Add to Cart</button> </div> ); }); export default ProductCard;
通过上述属性传递和事件回调机制,确保了父子组件间数据交互的清晰和可维护性,使整个组件体系易于理解和扩展。