How to correctly wrap few TD tags for JSXTransformer?

本小妞迷上赌 提交于 2019-11-28 17:44:41

So you have pairs of <td> elements which you want to return from a .map. The easiest way to do this is to just wrap them in an array.

<tr>
  {data.map(function(x, i){
    return [
      <td>{x[0]}</td>,
      <td>{x[1]}</td>
    ];
  })}
</tr>

Don't forget the comma after the first </td>.

The following error usually occurs when you are returning multiple elements without a wrapping element

Adjacent XJS elements must be wrapped in an enclosing tag

Like

return (
    <li></li>
    <li></li>
);

This doesn't work because you are effectively returning two results, you need to only ever be returning one DOM node (with or without children) like

return (
    <ul>
        <li></li>
        <li></li>
    </ul>
);

// or 

return (<ul>
    {items.map(function (item) {
        return [<li></li>, <li></li>];
    })}
</ul>);

For me to properly answer your question could you please provide a JSFiddle? I tried to guess what you're trying to do and heres a JSFiddle of it working.

When using the div as a wrapper its actually never rendered to the DOM (not sure why).

<tr data-reactid=".0.0.$1">
    <td class="info" data-reactid=".0.0.$1.$0.0">1</td>
    <td data-reactid=".0.0.$1.$0.1">2</td>
    <td class="info" data-reactid=".0.0.$1.$1.0">1</td>
    <td data-reactid=".0.0.$1.$1.1">2</td>
    <td class="info" data-reactid=".0.0.$1.$2.0">1</td>
    <td data-reactid=".0.0.$1.$2.1">2</td>
    <td class="info" data-reactid=".0.0.$1.$3.0">1</td>
    <td data-reactid=".0.0.$1.$3.1">2</td>
</tr>

With the release of React 16, there is a new component called Fragment. If are would like to return a collection of elements/components without having to wrap them in an enclosing element, you can use a Fragment like so:

import { Component, Fragment } from 'react';

class Foo extends Component {

  render() {
    return (
      <Fragment>
        <div>Hello</div
        <div>Stack</div>
        <div>Overflow</div>
      </Fragment>
    );
  }
}

Here is how you will do it

<tbody>
    {this.props.rows.map((row, i) =>
      <tr key={i}>
        {row.map((col, j) =>
          <td key={j}>{col}</td>
        )}
      </tr>
    )}
</tbody>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!