简体   繁体   English

在 React 中渲染数组/对象

[英]Rendering an array/object in React

I have a code that works but I don't understand why I am returning an array of react components and they are still rendering in the page... how does this work?我有一个有效的代码,但我不明白为什么我要返回一个反应组件数组并且它们仍在页面中呈现......这是如何工作的?

render() {
        const boxes = Array.from({ length: this.props.numBoxes }).map(() => (
            <Box colors={this.props.allColors} />
        ));

        console.log(boxes);

        return <div className='BoxContainer'>{boxes}</div>;

Each XML-like JSX tag is actually an object.每个类似 XML 的JSX标签实际上是一个 object。 As you can probably see in your console.log an array of objects, which React's internals use to render, monitor and update the components.正如您可能在console.log中看到的那样,有一个对象数组,React 的内部使用这些对象来渲染、监视和更新组件。 So simply <div className="boxContainer"></div> is an object in which's properties also contains it's children.所以简单地说<div className="boxContainer"></div>是一个 object ,其中的属性也包含它的孩子。

On the other hand, boxes results to an array of objects;另一方面, boxes会导致对象数组; you can replace {boxes} with:您可以将{boxes}替换为:

{<Box colors={this.props.allColors} />
<Box colors={this.props.allColors} />
<Box colors={this.props.allColors} />
...
<Box colors={this.props.allColors} />
<Box colors={this.props.allColors} />}

for JSX {boxes} means put everything in boxes variable in the place I put {boxes} with two curly braces surrounding it.对于JSX {boxes}意味着将所有内容都放在boxes变量中,在我放置{boxes}的地方用两个花括号包围它。

You can suppose boxes is equivalent to:你可以假设boxes相当于:

<Box colors={this.props.allColors} />
<Box colors={this.props.allColors} />
<Box colors={this.props.allColors} />
...
<Box colors={this.props.allColors} />
<Box colors={this.props.allColors} />

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

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