2017-12-30 29 views
2
내가 두 배열이

,의 내가 소품을 가지고 단어 및 정의(기본 반응)

export default class Dictionary extends React.Component { 
 
    constructor(props) { 
 
    super(props); 
 
    this.state = { 
 
     word: [], 
 
     definition:[], 
 
     index: 0 
 
    };  
 
}

을 가정 해 봅시다

<Card word = {w} definition = {d}/> 

와 나는 배열의 각 단어/정의 쌍에 대해이 카드의 목록을 표시합니다. 5 개 단어/정의가있는 경우에, 나는이 카드 5는 ScrollableView에 표시 할. 어떻게해야합니까? 감사! 당신이 할 수있는

답변

2

Array.prototype.map 함수의 콜백에서 Array.prototype.map function.The 두 ​​번째 인수가 인덱스를 사용합니다. 그런 다음이 배열을 렌더링하는 함수를 작성

dictionary: [ 
    { 
    index: 0, 
    word: 'Car', 
    definition: 'Definition of car', 
    }, 
    // More objects like the one above 
] 

: 당신은 당신이 같은 한 가지의 단어와 정의를 병합 할 수 귀하의 상태에서이

export default class Dictionary extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     word: ["a","b","c"], 
     definition:["a","b","c"], 
     index: 0 
    };  

    render() { 
     <div> 
     {this.state.word.map((w,i) => { 
      return <Card word = {w} definition = {this.state.definition[i]}/> 
     })} 
     </div> 
    } 
} 
2

같은 해당 definition 항목을 표시하는 데 그 인덱스를 사용할 수 있습니다 개체는 같은 수 :

renderDictionary() { 
    return (this.state.dictionary.map(word => { 
    <Card key={word.index} word={word.word} definition={word.definition} /> 
    })); 
} 

그리고 당신은 단지 함수를 호출 :

export default class Dictionary extends React.Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     dictionary: [ 
     { 
      index: 0, 
      word: 'Car', 
      definition: 'Definition of car', 
     }, 
     // More objects like the one above. 
     ], 
    }; 
    } 

    renderDictionary() { 
    return (this.state.dictionary.map(word => { 
     <Card key={word.index} word={word.word} definition={word.definition} /> 
    })); 
    } 

    render() { 
    return (
     <View> 
     {this.renderDictionary()} 
     </View> 
    ); 
    } 
}