Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将相同的道具和文本呈现给不同组件类型的干反应方法_Javascript_Reactjs_React Native_Design Patterns - Fatal编程技术网

Javascript 将相同的道具和文本呈现给不同组件类型的干反应方法

Javascript 将相同的道具和文本呈现给不同组件类型的干反应方法,javascript,reactjs,react-native,design-patterns,Javascript,Reactjs,React Native,Design Patterns,在React中,是否有推荐的或行业标准的技术用于有条件地呈现具有相同道具和innerHTML的不同组件类型 具体来说,我在React Native中在和之间交换 我会检查状态,如果blah为true,则渲染,否则。但是,它们将使用相同的道具/内部文本 例如: 不干 var component = <CoolComponent quantity="42" color="green" write="true">some stuff</CoolComponent>; if (t

在React中,是否有推荐的或行业标准的技术用于有条件地呈现具有相同道具和innerHTML的不同组件类型

具体来说,我在React Native中在和之间交换

我会检查状态,如果blah为true,则渲染,否则。但是,它们将使用相同的道具/内部文本

例如:

不干

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>;

如果愿意,可以将其提取到专用组件。在这个案例中只需使用&即可

const NewComponent = ({ props }) => (
  your_condition ?
    <ADifferentOne {...props} /> :
    <ANewComponent {...props} />
)

如果愿意,可以将其提取到专用组件。在这个案例中只需使用&即可

const NewComponent = ({ props }) => (
  your_condition ?
    <ADifferentOne {...props} /> :
    <ANewComponent {...props} />
)
用法:

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

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