【问题标题】:Reactjs switching between componentsReactjs 在组件之间切换
【发布时间】:2017-10-07 11:54:13
【问题描述】:

我在我的 react 应用程序中渲染了 3 个组件

之前我是使用状态渲染它们

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

通过将状态设置为 true 并将所有其他状态设置为 false 来呈现我想要的状态

并渲染它们

 <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

现在重构了一点点。

我只有一个以组件为值的状态

如果我需要在组件之间切换,我只需更改它的状态

为了传递道具,我使用了这个第三方包

获取当前组件名和一些条件逻辑传入props

我的问题是哪种方法更好

所有组件都处于状态 并将值设置为 true,其他所有设置为 false。

具有直接作为其值传入的组件的一种状态。

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

更多州还是一个额外的包裹?

【问题讨论】:

    标签: reactjs ecmascript-6


    【解决方案1】:

    减少为协调状态变化所做的工作在这里始终是一种成功的方法。因此,更好的方法是为组件直接传入一个状态作为其值

    如果每次只显示 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>
    

    【讨论】:

      猜你喜欢
      • 2021-05-26
      • 2020-09-20
      • 2020-03-20
      • 2019-12-07
      • 2016-03-08
      • 2018-09-13
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      相关资源
      最近更新 更多