使用React,我如何基于类型呈现组件

Using React, how do I render components based on a type?

本文关键字:类型 组件 何基于 React 使用      更新时间:2023-09-26

假设我有一个Posting组件列表,可以是汽车,卡车或船的类型。

渲染每种类型的帖子的道具是相同的,只是布局不同。

我应该为每个类型创建一个单独的组件吗?(CarPosting, TruckPosting),然后根据type道具渲染正确的一个,或者我应该对Posting组件中的每种类型都有一个部分渲染方法,然后我从主渲染方法切换和调用?

您应该为每个posting设置一个单独的组件,然后包装器组件应该决定渲染哪个内部组件。

内部组件

你应该为每种类型(CarPosting, TruckPosting…)都有一个单独的组件。这些组件不应该有type属性,因为当它们被渲染时,渲染者应该知道它们是否为CarPosting

至于是否应该对这些组件使用继承,这取决于它们在逻辑上共享的程度。如果它们只共享一些prop名称,仅凭这一点并不能证明使用继承是合理的。事实上,在大多数情况下,React组件不需要继承。有一些方法可以在没有继承的情况下在组件之间共享行为,比如使用Mixins或简单地共享一些JS模块。

包装器组件

现在,包装器组件应该根据子组件的类型确定要呈现哪些子组件。

是的,您可以执行switch并选择该switch中的组件。如果你只有2或3个组件类型,你不太关心可扩展性,这是可以接受的。

然而,更复杂的解决方法是使用ComponentFactory,其中注册type和组件,像这样:

// the first parameter is the type, the second is the Component
componentFactory.register("car", CarPosting);
componentFactory.register("boat", BoatPosting);

componentFactory可以有一个buildComponent方法接受props,并根据您注册的内容将props重新传递给组件的新实例。

的例子:

componentFactory.buildComponent("boat", someBoatProps)

现在,可以从包装器组件调用componentFactory为您生成组件。这样的:

// this is inside the render method
<div>
 {
     postings.map(posting => componentFactory.buildComponent(posting.type, someOtherProps))
 }
 </div>