首页 文章

DRY React将相同的道具和文本渲染到不同组件类型的方法

提问于
浏览
1

在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 回答

  • 1

    如果您愿意,可以将其提取到专用组件 . 在这种情况下,只需使用ternary operatorspread object

    const NewComponent = ({ props }) => (
      your_condition ?
        <ADifferentOne {...props} /> :
        <ANewComponent {...props} />
    )
    
  • 3
    const ComponentSwitcher = ({ props }) => {
      return props.if ? <props.onTrue {...props} /> : <props.onFalse {...props} />
    }
    

    用法:

    <ComponentSwitcher if={myVar} onTrue={ADifferentOne} onFalse={ANewComponent
    } quantity="42" color="green" write="true">some stuff</ComponentSwitcher>
    

相关问题