2017-09-28 125 views
0

我有一个应用程序在3个不同的国家(接近电子商务)运行。每个国家都有一个开发团队,可以根据需要更改某些特定的component。我正在考虑通过上下文传递组件,但是如何选择Form-USForm-UK,例如? (思考动态导入它不可能在反应)使用React动态渲染组件

我App.js

import React from 'react' 
import UserInput from './common/UserInput' 

class App extends React.Component { 

    getChildContext() { 
    return { 
     input: UserInput 
    } 
    } 

    render() { 
    return (
     <div> 
     {this.props.children} 
     </div> 
    ) 
    } 
} 

App.childContextTypes = { 
    input: React.PropTypes.object 
} 

export default App 

我挑组件所需的那样时:

render() { 
    const Input = this.context.input 
    return (
     <Input placeholder='Input Test'/> 
    ) 
} 

这工作得很好,但其那是一个很好的做法?有更好的方法来做到这一点,我怎样才能添加一个具有特定名称的组件?

+0

使用上下文很危险,除非你确切地知道你在做什么。如何让孩子导入所有可能的组件,并让父母传递哪个组件作为道具? – dshapiro

+0

@dshapiro它也是一种可能性。那么使用'require('Component - $ {COUNTRY}')'而不是导入所有可能的孩子? –

+1

我并不熟悉要求确定这是否可行。如果团队在编译时只需要不同的组件(就像听起来那样),那么你也可以在构建过程中做一些事情。例如,你可以有一个“国家”配置选项,导致该国家的组件被导出为“输入”,然后始终有父级使用“输入”。 – dshapiro

回答

1

正如我们在评论中所讨论的,有更聪明的方法可以做到这一点。但是,如果我需要一个解决方案,今天这个,这是我会怎么做:

index.js为“输入”

import ComponentUS from './Component-US'; 
import ComponentBR from './Component-BR'; 
import ComponentAG from './Component-AG'; 
import config from '../config.json'; 

let thingToExport; 
if (config.country === 'US') { 
    thingToExport = ComponentUS; 
} else if (config.country === 'BR') { 
    thingToExport = ComponentBR; 
} else { 
    thingToExport = ComponentAG; 
} 
export default thingToExport; 

然后家长可以只需要导入Input从index.js。