React
cannot appear as a child of Warning

前端 未结 2 616
有刺的猬
有刺的猬 2021-01-17 22:02

I am getting the following warnings in a React component:

The related code is the following:

import React, { PropTypes } from \'react\';
imp         


        
相关标签:
2条回答
  • 2021-01-17 22:48

    There are two problems with your code

    1. Only td and th are allowed inside tr
    2. In React version < 15, you have to wrap tags in one element, when you try to render them. In React 16, you can now do the following :

      [
        <td key={1}>{params.data.firstName}&nbsp;</td>,
        <td key={2}>{params.data.lastName}&nbsp;</td>
      ]
      

      instead of wrapping the tds inside a div

    I also suggest you extract your logic outside of the tr

    0 讨论(0)
  • 2021-01-17 22:52

    If you need to return several elements and can't have a wrapper (such as in this case), you have a new option as of React 16.2. Fragments:

    <React.Fragment>
      <td>{params.data.firstName}&nbsp;</td>
      <td>{params.data.lastName}&nbsp;</td>
    </React.Fragment>
    

    Or, you might be able to simplify it as:

    <>
      <td>{params.data.firstName}&nbsp;</td>
      <td>{params.data.lastName}&nbsp;</td>
    </>
    

    The fragments won't resolve to any HTML element, so the <td>s will be direct children of your <tr>.

    0 讨论(0)
提交回复
热议问题