(React Native)显示数组中项目的卡列表

问题描述 投票:2回答:2

我有两个数组,让我们说一下单词和定义

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

我有一个道具

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

我想为数组中的每个字/定义对显示这些卡的列表。如果有5个单词/定义,那么我想要在ScrollableView中显示其中5个这样的卡片。我怎样才能做到这一点?谢谢!

javascript reactjs mobile native
2个回答
2
投票

你可以使用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>
    }
}

2
投票

在你的州,你可以合并单词和定义,例如:

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>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.