在JSX中返回多个元素 [英] Returning multiple elements in JSX

查看:79
本文介绍了在JSX中返回多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户未登录,我正在尝试返回两个链接。这样的事情:

I'm trying to return two links if the user is not logged in. Something like this:

<Nav>
    {if(this.state.user) {
        <NavItem onClick={this.logout}>Log out</NavItem>
    } else {
        <NavItem onClick={this.login}>Log in</NavItem>
        <NavItem onClick={this.register}>Register</NavItem>
    }
    }
</Nav>

我知道我可以用三元运营商做到这一点:

I know I can do this with a ternary operator:

<Nav>
    {this.state.user ?
        <NavItem onClick={this.logout}>Log out</NavItem>
        :
        <NavItem onClick={this.login}>Log in</NavItem>
    }
</Nav>

问题是我想渲染两个NavItems。我看到我可以使用函数来完成它,但当我尝试在这样的函数中执行它时:

The problem is I want to render the two NavItems. I saw I can do it with a function, but when I try to do it in a function like this:

myFunction(){
    return(
        <NavItem onClick={this.login}>Zaloguj się</NavItem>
        <NavItem onClick={this.login}>Zaloguj się</NavItem>
    )
}

它告诉我第二个元素无法访问休息。那我怎么能回归两个元素呢?对代码进行字符串化没有帮助

It tells me that the second element is unreachable and breaks. So how can I return two elements? Stringifying the code doesn't help

推荐答案

如果您使用的是React v16以下的版本,则只能在<$返回一个元素c $ c> jsx ,所以你必须将你的元素包装在一个:

If you are using a version below React v16 you can only return one element in jsx, so you have to wrap your elements inside one:

<div>
 <NavItem onClick={this.login}>Zaloguj się</NavItem>
 <NavItem onClick={this.login}>Zaloguj się</NavItem>
</div>

如果你使用React v16并且abose,你可以使用碎片

If you are using React v16 and abose you can use Fragments

import React, { Fragment } from 'react';

...
...

    <Fragment>
     <NavItem onClick={this.login}>Zaloguj się</NavItem>
     <NavItem onClick={this.login}>Zaloguj się</NavItem>
    <Fragment/>

您还可以返回元素数组在此宣布

You could also return an Array of Elements as announced here:

 return [
    <NavItem key="1" onClick={this.login}>Zaloguj się</NavItem>,
    <NavItem key="2" onClick={this.login}>Zaloguj się</NavItem>
  ];

如果您使用的是React v16.2.0及更高版本,则可以使用较短版本的片段

If you are using React v16.2.0 and above you can use the shorter version of Fragments

<>
 <NavItem onClick={this.login}>Zaloguj się</NavItem>
 <NavItem onClick={this.login}>Zaloguj się</NavItem>
</>

根据您的环境,您可能无法使用所有这些解决方案:支持片段

Depending on your environment you might not be able to use all of these solutions: support for fragments

这篇关于在JSX中返回多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆