简体   繁体   English

为什么放置一个 div 标签允许这个 React 代码编译?

[英]Why does putting a div tag allow this React code to compile?

I found a solution to an issue on my own, but I am confused why it worked and would like to learn more.我自己找到了一个问题的解决方案,但我很困惑它为什么有效,并想了解更多信息。

I have the following code that has a run time error:我有以下代码有运行时错误:

class ExampleClass extends React.Component {
  render() {
    const foo = [1, 2, 3]
    const jsx = foo.map((num) =>
      <span key={num}>
        {num}
      </span>
    );

    return(
      {jsx}
    )
  }
}

To this, I get "Error: Objects are not valid as a React child (found: object with keys {jsx}). If you meant to render a collection of children, use an array instead."为此,我得到“错误:对象作为 React 子对象无效(找到:对象带有键 {jsx})。如果您打算渲染子对象集合,请改用数组。”

However, if I instead do this:但是,如果我改为这样做:

class ExampleClass extends React.Component {
  render() {
    const foo = [1, 2, 3]
    const jsx = foo.map((num) =>
      <span key={num}>
        {num}
      </span>
    );

    return(
      <div>
        {jsx}
      </div>
    )
  }
}

It works, outputting 123 on the page.它的工作原理,在页面上输出123 Why do I need a <div> tag?为什么我需要<div>标签? Doesn't the jsx variable have the tags necessary to insert it into html? jsx变量没有将其插入 html 所需的标签吗?

Thats because you are literaly returning a object那是因为你实际上是在返回一个对象

Consider this:考虑一下:

class ExampleClass extends React.Component {
  render() {
    const foo = [1, 2, 3]

    const jsx = foo.map((num) =>
      <span key={num}>
        {num}
      </span>
    );

    return ({jsx})
  }
}

You are returning an object with only one key called jsx , with the value of the variable jsx declared just before.您正在返回一个只有一个名为jsx键的对象,变量jsx的值jsx声明。

Every JSX should return at it's outer most wrapper must be:每个 JSX 都应该在它最外层的包装器处返回:

  1. A pair of tags:一对标签:

const Component = () => { return ( <div> ...JSX </div> ) }

  1. A React.Fragment :一个React.Fragment

const Component = () => { return ( <> ...JSX </> ) }

  1. A component:一个组件:

const Component = () => { return ( <ReturnedComponent /> ) }

When returning anything in jsx, it can only return one element.在jsx中返回任何东西时,它只能返回一个元素。 When returning only {jsx}, you are returning multiple span elements, which is not allowed.当仅返回 {jsx} 时,您将返回多个 span 元素,这是不允许的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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