在React.render()中返回多个元素 [英] Return multiple elements inside React.render()

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

问题描述

我是新来的人,遇到了这个问题:

I am new in react and I encountered with this problem:

render: function(){
    return (
        <h3>Account</h3>
        <a href="#" onClick={some_event}>Login</a>
        <a href="#" onClick={some_event}>Logout</a>
)}

当我这样渲染时,它会给我类似multiple components must wrapt with end

When I am rendering like this it gives me error saying like multiple components must wrapt with end

我应该为每个html标签或每一行创建一个componenet,还是可以用这种方式呈现.

Should I make one componenet for each html tag or each line or I can render in that way..

有什么建议吗?

推荐答案

在React中< v16.0 render方法只能呈现单个根节点. (更新:此版本在v16中已更改,请参见下文).在您的情况下,您将返回3个节点.为了解决这个问题,您可以将3个节点包装在一个根节点中:

In React < v16.0 the render method can only render a single root node. (update: this is changed in v16, see below). In your case, you're returning 3 nodes. To get around this you can wrap your 3 nodes in a single root node:

render: function(){
  return (
    <div>
      <h3>Account</h3>
      <a href="#" onClick={some_event}>Login</a>
      <a href="#" onClick={some_event}>Logout</a>
    </div>
)}

在React v16中,render()可能返回一个元素数组.

In React v16 it's possible for render() to return an array of elements.

与其他数组一样,您需要向每个元素添加一个键,以避免出现键警告:

Like with other arrays, you’ll need to add a key to each element to avoid the key warning:

render() {
  return [
    <ChildA key="key1" />,
    <ChildB key="key2" />,
    <ChildC key="key3" />,
  ];
}

另一种选择是使用片段.片段使您可以将子级列表分组,而无需在DOM中添加额外的节点.

Another option is to use a Fragment. Fragments let you group a list of children without adding extra nodes to the DOM.

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}

还有一种用于声明片段的简短语法(<>):

There is also a short syntax (<>) for declaring fragments:

render() {
  return (
    <>
      <ChildA />
      <ChildB />
      <ChildC />
    </>
  );
}

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

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