簡體   English   中英

(反應本機)顯示陣列中物品的卡片列表

[英](React Native) Displaying a list of cards for items in an array

我有兩個數組,假設單詞和定義

 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中。 我怎樣才能做到這一點? 謝謝!

您可以使用Array.prototype.map函數Array.prototype.map函數的回調中的第二個參數是index。 您可以使用該索引來顯示相應的definition項,如下所示

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>
    }
}

在您的狀態下,您可以將單詞和定義合並為一件事,例如:

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} />
  }));
}

然后,您只需調用該函數:

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>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM