【问题标题】:(React Native) Displaying a list of cards for items in an array(React Native) 显示数组中项目的卡片列表
【发布时间】:2017-12-30 05:27:48
【问题描述】:

我有两个数组,比如说 单词和定义

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 中。我怎样才能做到这一点?谢谢!

【问题讨论】:

    标签: javascript reactjs mobile native


    【解决方案1】:

    你可以使用Array.prototype.map函数。Array.prototype.map函数回调中的第二个参数是索引。您可以使用该索引来显示相应的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>
          );
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-02-25
        • 1970-01-01
        • 1970-01-01
        • 2020-04-26
        • 2022-01-13
        • 1970-01-01
        • 1970-01-01
        • 2019-02-15
        • 1970-01-01
        相关资源
        最近更新 更多