闽公网安备 35020302035485号
3.提高组件的可复用性和扩展性,减少重复代码。
import React from "react";
import ComponentA from "./ComponentA";
import ComponentB from "./ComponentB";
function App() {
const condition = true;
return (
<div>
{condition ? <ComponentA /> : <ComponentB />}
</div>
);
}
export default App;
在上面的示例中,我们通过一个条件变量condition来决定渲染哪个组件。如果condition为true,则渲染ComponentA组件;如果condition为false,则渲染ComponentB组件。通过这种方式,我们可以根据不同的条件渲染不同的组件。import React from "react";
function ShirtIcon() {
return (
<div>
<img src="shirt-icon.png" alt="Shirt Icon" />
</div>
);
}
function ShoeIcon() {
return (
<div>
<img src="shoe-icon.png" alt="Shoe Icon" />
</div>
);
}
export { ShirtIcon, ShoeIcon };
接下来,在我们的购物应用中,我们根据商品类型来决定显示哪个图标。我们可以使用动态组件来实现这个功能,让我们来看一下代码:import React from "react";
import { ShirtIcon, ShoeIcon } from "./Icons";
function Product({ type }) {
const components = {
shirt: ShirtIcon,
shoe: ShoeIcon,
};
const ProductIcon = components[type];
return (
<div>
<h2>Product Details</h2>
<ProductIcon />
<p>Type: {type}</p>
</div>
);
}
function App() {
return (
<div>
<Product type="shirt" />
<Product type="shoe" />
</div>
);
}
export default App;
在上面的示例中,我们定义了一个Product组件,它接收一个type属性来决定商品的类型。根据商品类型,我们使用一个对象components来映射对应的组件。然后,我们根据type属性从components中获取对应的组件,并将其赋值给ProductIcon变量。最后,我们在组件中渲染ProductIcon组件,实现了根据商品类型动态显示不同的图标。