2017-12-30 35 views
2

の項目のためのカードのリストを表示する私は2つの配列を持って、私は小道具(ネイティブに反応)配列

<Card word = {w} definition = {d}/> 
を持っているのは、 言葉と定義

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

をしましょう

とし、配列内の各単語/定義のペアについて、これらのカードのリストを表示したいとします。 5つの単語/定義がある場合、これらのカードのうちの5つをScrollableViewに表示します。これどうやってするの?ありがとう!

答えて

2

Array.prototype.map関数を使用できます。Array.prototype.map関数のコールバックの2番目の引数はインデックスです。その後、この配列をレンダリングする関数を記述

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> 
    ); 
    } 
} 
関連する問題