简体   繁体   English

如何在React组件中重复两个元素

[英]How to repeat two elements in a react component

I am using semantic ui and I need to build an accordion component. 我正在使用语义ui,我需要构建一个手风琴组件。 So this is what I come up with, but this doesn't work as the usage of .title and .content is wrong. 所以这就是我想出的,但是由于.title.content的使用是错误的,所以这不起作用。 How should this be done correct? 应该如何正确做到这一点?

import React, { Component } from 'react';

export default class Example extends Component {
    getData() {
        // some data
    }

    render() {
        return (
            <div className="ui styled fluid accordion">
                {
                    this.getData().map((element) => {
                        return (
                            <div className="title">
                                <i className="dropdown icon"></i>
                                { element.title }
                            </div>
                            <div className="content">
                                <ul className="ui list">
                                    <li>Lorem ipsum</li>
                                </ul>
                            </div>
                        );
                    })
                }
            </div>
        );
    }
}

Update 更新

The result should be like 结果应该像

<div class="ui accordion">
    <div class="active title">
    </div>
    <div class="active content">
    </div>
    <div class="title">
    </div>
    <div class="content">
    </div>
</div>

You can return only one component from a function. 您只能从函数中返回一个组件。

In your case the map is a wrong choice. 在您的情况下, 地图是错误的选择。 Try this in your render function: 渲染函数中尝试以下操作:

// build the array of all elements
const accordionChildren = [];
this.getData().forEach(element => {
  accordionChildren.push(
    <div className="title">{element.title}</div>,
    <div className="content">{element.content}</div>
  );
});

return (
  <div className="ui styled fluid accordion">
    {accordionChildren}
  </div>
);

It's invalid syntax to return two components in any part of the code. 在代码的任何部分返回两个组件是无效的语法。 The issue is this snippet: 问题是以下代码段:

...

return (
    <div className="title">
        <i className="dropdown icon"></i>
        { element.title }
    </div>
    <div className="content">
        <ul className="ui list">
            <li>Lorem ipsum</li>
        </ul>
    </div>
);

...

However, you should be able to get them to render next to each other by returning an array: 但是,您应该能够通过返回一个数组使它们彼此相邻渲染:

...

return (
    [(<div className="title">
        <i className="dropdown icon"></i>
        { element.title }
    </div>),
    (<div className="content">
        <ul className="ui list">
            <li>Lorem ipsum</li>
        </ul>
    </div>)]
);

...

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

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