2017-10-07 57 views
0

我有3个组成部分,我在我的渲染之间的切换反应应用Reactjs组件

以前我是用状态

state = { 
    one: true, 
    two: false, 
    three: false 
} 

渲染,我想它的状态设置为true,所有的一个使它们其他假

,并使得它们

<div> 
     { 
     this.state.one && 
     <Start 
      switchDisplay={ this.switchDisplay } 
      quizname={ quizname } 
      author={ author } 
     /> 
     } 
     { this.state.two && 
     <Playground 
      {...this.state.currentQuestion} 
      onclick={this.nextQuestion} 
     /> 
     } 
     { 
     this.state.three && 
     <Score nominator={this.result} denominator={entry.length}/> 
     } 
    </div> 

(不要考虑一下道具)

后来我现在重构律位后,使用第三方软件包

https://www.npmjs.com/package/react-display-name 

我有具有组分作为它的值

和如果我需要的部件之间的开关I只是改变它的状态

和道具通过我用该第三只有一个状态方包

获得当前组件的名称和一些有条件的逻辑在道具

我的问题是这是更好的方法

将所有组件的状态设置为 ,并将该值设置为true,将所有其他设置为false。

具有用于该组件的一个状态直接传递在作为其值。

并使用“第三方包”获取当前渲染的组件的显示名称,并使用组件的名称传递道具。

更多状态或一个额外的包?

回答

3

为了调和状态变化而做的减少工作总是在这里取胜。因此,更好的方法是对于直接传入的组件具有一个状态,其值为

如果每次只显示3个组件中的一个,则可能不需要外部库。

constructor()

const state = { 
    display: 'start', 
}; 

this.state = state; 

电线用于与对象键尽可能状态的所有3个分量的查找对象值

const gameComponentRegistry = { 
    'start': Start, 
    'playground': Playground, 
    'score': Score, 
} 

export default gameComponentRegistry; 

render(),进口和查找组件呈现在gameComponentRegistry

const component = gameComponentRegistry[this.state.display]; 
const props = {}; // makeup props 
<div> 
    { <component ...props /> } 
</div>