简体   繁体   English

React / JSX动态组件数

[英]React / JSX Dynamic Number of Components

In React, is it possible to render a variable number of HTML tags or React Components? 在React中,是否可以呈现可变数量的HTML标签或React组件?

For example, in the code below, this.renderStats() can render 0 to 2 <i> tags depending on the variables stats.health and stats.energy . 例如,在下面的代码中, this.renderStats()可以根据变量stats.healthstats.energy渲染0至2个<i>标签。

The following code prints out [object Object] 下面的代码打印出[object Object]

class Hero extends React.Component {

    showBadges(stats) {
        let badgeList = []
        if (stats.health > 1000) {
            badgeList += <i className="fa fa-times-circle" style={{color: "red"}}></i>
        }
        if (stats.energy > 100) {
            badgeList += <i className="fa fa-times-circle" style={{color: "blue"}}></i>
        }
        return badgeList;
    }

    renderStats() {
        return this.props.users.map((stats) => {
            return (
                <Td className="align-middle" column="badges">{ this.showBadges(stats) }</Td>
            );
        });
    }

    render() {
        return ( 
            <Table>
                { this.renderStats() } 
            </Table>
        );
    }

}

Change your showBadges function to: 将您的showBadges函数更改为:

showBadges(stats) {
    let badgeList = []
    if (stats.health > 1000) {
       badgeList.push(<i className="fa fa-times-circle" style={{color: "blue"}}></i>)
    }
    if (stats.energy > 100) {
       badgeList.push(<i className="fa fa-times-circle" style={{color: "blue"}}></i>)
    }
    return badgeList;
}

And it should work. 它应该工作。

You can either create a list of children dynamically as @Boky pointed out or take a full advantage of JSX and use inline expressions: 您可以按照@Boky指出的动态创建子列表,也可以充分利用JSX并使用内联表达式:

showBadges(stats) {
  return (
    <span>
      {
        stats.health > 1000 &&
        <i className="fa fa-times-circle" style={{color: "blue"}}></i>
      }
      {
        stats.energy > 100 &&
        <i className="fa fa-times-circle" style={{color: "blue"}}></i>
      }
    </span>
  )
}

You can use either simple boolean expression ( condition && <Component /> ) or ternary operator ( condition ? <ComponentIfTrue /> : <ComponentIfFalse /> ) 您可以使用简单的布尔表达式condition && <Component /> )或三元运算符condition ? <ComponentIfTrue /> : <ComponentIfFalse />

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

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