在React中,是否有推荐的或行业标准的技术来有条件地渲染具有相同props和innerHTML的不同组件类型?
具体来说,我在React Native中交换 <Text />
和 <TextInput />
.
我会检查状态,如果等等是真的那么渲染 <ComponentA />
,否则 <ComponentB />
. 但是他们会采用相同的道具/ innerText .
举个例子:
不干
var component = <CoolComponent quantity="42" color="green" write="true">some stuff</CoolComponent>;
if (true) {
component = <ADifferentOne quantity="42" color="green" write="true">some stuff</ADifferentComponent>;
} else if (false) {
<ANewComponent quantity="42" color="green" write="true">some stuff</ANewComponent>
}
我发现的最佳解决方案是:
var TagType = CoolComponent;
if (true) {
TagType = ADifferentOne;
} else if (false) {
TagType = ANewComponent
}
<TagType quantity="42" color="green" write="true">Some stuff</TagType>;
2 回答
如果您愿意,可以将其提取到专用组件 . 在这种情况下,只需使用ternary operator&spread object
用法: