2016-10-03 2 views
0

변수에 'numpad'문자열이 있다는 것을 알고있을 때 어떻게 동일한 이름의 구성 요소를 간단하게 렌더링 할 수 있습니까? 구성 요소 Numpad, UnitList, ShiftList 및 개별적으로 렌더링하고 싶습니다. 내 아이에게 콜백을 만들고 있는데, 부모로부터 렌더링하고 싶은 구성 요소 (문자열)를 다시 보냅니다. 그런 다음 numPad, unitList 또는 shiftList 변수를 설정 한 다음이 구성 요소를 렌더링하려고합니다. 쓰기 스위치보다 더 간단한 방법이 있습니까? 스위치로 나는 단지 -스위치보다 더 간단하고 짧은 방법으로 대체 - reactjs

switch(type){ 
    case 'numpad': 
     <Numpad .../> 
     break; 
    case 'unitList': 
    ..... 

} 

을 찾을 수 있지만 좀 더 간단하고 짧은 것을 찾고 있습니다. 지금은

난이 -

자녀의 구성 요소에서
render(){ 
     return(
     <div> 
      <Child update={this.renderSomeComponent.bind(this)} /> 
      {(() => { 
        switch (this.state.type) { 
         case "numpad": return <Numpad ../>; 
         case "unitList": return <UnitList ../>; 
         case "shiftList": return <ShiftList ../>; 
         case "sideList": return <SideList ../>; 
         default:  return false; 
        } 

      })()} 
     </div> 
    ) 
} 

renderSomeComponent(type){ 
    this.setState({ 
      type: type 
     }) 
} 

내가있는 방법 - 일반적으로

handleClick(){ 
     this.props.update(this.props.type); 
    } 
+0

내가하려는 일에 대해 더 많은 코드를 공유해야한다고 생각합니다. 그렇게 명확하지 않습니다. – cdagli

+0

좋아, 기다려 : D –

+0

'this.state.type'을 어디에 설정합니까? 아이는'rednerSomeComponent'를 어떻게 사용합니까? –

답변

0

, 당신은 switch ... case을 피하고자 할 때, 당신은 매핑을 처리하는 자바 스크립트 객체를 사용할 수 있습니다 .

const map = { 
    value1: output1, 
    value2: output2, 
    ... 
} 

위 준 다음, 다음과 같이 작성할 수 있습니다 코드 :

import React from "react"; 
import Numpad from "the-location-of-your-numpad-component"; 
import UnitList from "the-location-of-your-unitList-component"; 
... 

const mapTypeToComponent = { 
    numpad: Numpad, 
    unitList: UnitList, 
    ... 
} 

// In your component 
render(){ 
    const { type } = this.state; 
    const ComponentToShow = mapTypeToComponent[type]; 

    return(
    <div> 
     <Child update={this.renderSomeComponent.bind(this)} /> 
     <ComponentToShow /> 
    </div> 
) 
} 
당신의 예에서, 누구의 키 당신의 변수의 서로 다른 값은 그 값이 예상 출력 객체를 생성 의미

희망이 있습니다.

관련 문제