将字典键映射到行并显示其值

时间:2020-09-17 22:27:57

标签: javascript reactjs

我在props组件中有一个设置为React的词典列表,如下所示:

console.log(fruits): [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ] 

命令:

0:
name: 'Apple'
color: 'Red'

1:
name: 'Banana'
color: 'Yellow'

2:
name: 'Pear'
color: 'Green'

....

我需要在各行中显示其名称,每行基于各自的水果颜色:

class Basket extends Component {
  constructor(props) {
    super(props);

    this.state = {
      fruits:[],
      isLoaded:false
    };
  }

render() {

        const { fruits } = this.props;
        console.log(fruits)

        return (
     <div className="app">
        <div className="fruit-wrapper">
          <div className="row">
            <Fruit>Apple</Fruit>
            <Fruit>Red 2</Fruit>
            <Fruit>Red 3</Fruit>
          </div>
          <div className="row">
            <Fruit>Banana</Fruit>
            <Fruit>Yellow 2</Fruit>
            <Fruit>Yellow 3</Fruit>
          </div>
            <div className="row">
            <Fruit>Pear</Fruit>
            <Fruit>Green 1</Fruit>
            <Fruit>Green 2</Fruit>
          </div>
          </div>
        </div>
      </div>
    );
  }

导出默认购物篮;


如何从列表中映射水果对象的值并显示水果名称,将每个名称分配给各自的行颜色?

1 个答案:

答案 0 :(得分:1)

Working sandbox

import React from "react";

function Fruit({ children }) {
  return <div>{children}</div>;
}

export default class Basket extends React.Component {
  state = {
    isLoaded: false
  };

  render() {
    const { fruits } = this.props;

    return (
      <div className="app">
        <div className="fruit-wrapper">
          {fruits.map(({ name, color }) => (
            <div className="fruit-wrapper">
              <Fruit>{name}</Fruit>
              <Fruit>{color} 2</Fruit>
              <Fruit>{color} 3</Fruit>
            </div>
          ))}
        </div>
      </div>
    );
  }
}
相关问题