Javascript 将相同的道具和文本呈现给不同组件类型的干反应方法
在React中,是否有推荐的或行业标准的技术用于有条件地呈现具有相同道具和innerHTML的不同组件类型 具体来说,我在React Native中在和之间交换 我会检查状态,如果blah为true,则渲染,否则。但是,它们将使用相同的道具/内部文本 例如: 不干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
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>