简体   繁体   中英

How to render inside a loop inside a JSX?

I would like make this to work:

import React from 'react';

export default class HelloWorld extends React.Component {

    public render(): JSX.Element {
        let elements = {"0": "aaaaa"};
        return (
            <table>
                <thead>
                    <td>Elements</td>
                    <td>Contenu</td>
                </thead>
                <tbody>
                {Object.values(elements).map((element, index => {
                <span>
                    {element.value}
                </span>
                })}
                </tbody>
            </table>
        );
    }

}

I wanna have a render inside a object.entries loop inside a render

export default class HelloWorld extends React.Component {
  public render(): JSX.Element {
    let elements = {"0": "aaaaa"};
    return (
      <table>
        <thead>
          <td>Elements</td>
          <td>Contenu</td>
        </thead>
        <tbody>
        {Object.values(elements).map((element, index) => {
          return <span>
            {element}
          </span>
        })}
        </tbody>
      </table>
    );
  }
}

In your solution you were missing end of parentheses in map and return also in map

You'll want to map over the values of the Object elements , but drop the .value lookup on each element, as that will be undefined.

export default class HelloWorld extends React.Component {
  public render(): JSX.Element {
    let elements = {"0": "aaaaa"};
    return (
      <table>
        <thead>
          <td>Elements</td>
          <td>Contenu</td>
        </thead>
        <tbody>
        {Object.values(elements).map((element, index) => (
          <span>
            {element}
          </span>
        ))}
        </tbody>
      </table>
    );
  }
}

It's also worth point out that an Object isn't the best way to store a list of data, an Array would be much simpler. Like so:

export default class HelloWorld extends React.Component {
  public render(): JSX.Element {
    const elements = [
      'aaa',
      'bbb',
      'ccc'
    ];
    return (
      <table>
        <thead>
          <td>Elements</td>
          <td>Contenu</td>
        </thead>
        <tbody>
        {elements.map((element, index) => (
          <span>
            {element}
          </span>
        ))}
        </tbody>
      </table>
    );
  }
}

You can convert your object values to an array using Object.values(your_object) and then map throw the array via the map method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM