在没有包装器元素的方法中返回多个React元素 [英] Return multiple React elements in a method without a wrapper element

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

问题描述

我正在尝试从辅助方法返回多个React元素。我可以通过移动一些代码来解决它,但我想知道是否有更清洁的方法来解决它。我有一个方法返回部分 render 方法,并且该函数需要返回React元素和一些文本。通过一个例子更清楚:

I'm trying to return multiple React elements from a helper method. I could solve it simply by moving around some code, but I'm wondering if there's a cleaner way to solve it. I have a method that returns part of the render method, and that functions needs to return both a React element and some text. It's clearer through an example:

class Foo extends React.Component {
  _renderAuthor() {
    if (!this.props.author) {
      return null;
    }

    return [
      ' by ',
      <a href={getAuthorUrl(this.props.author)}>{this.props.author}</a>,
    ]; // Triggers warning: Each child in an array or iterator should have a unique "key" prop.

  render() {
    return (
      <div>
        {this.props.title}
        {this._renderAuthor()}
      </div>
    );
  }
}

我知道 render 方法必须返回1个React元素。使用这样的辅助方法会触发警告,修复警告(通过添加键)会使代码过于复杂。是否有一种干净的方法可以在不触发警告的情况下执行此操作?

I know the render method has to return exactly 1 React element. Using a helper method like this would trigger a warning, and fixing the warning (by adding keys) would make the code too convoluted. Is there a clean way to do this without triggering a warning?

编辑:

另一个用例:

render() {
  return (
    <div>
      {user
        ? <h2>{user.name}</h2>
          <p>{user.info}</p>
        : <p>User not found</p>}
    </div>
  );
}

编辑2:

事实证明这是不可能的,我在这里写了大约2个解决方法: https://www.wptutor.io/web/js/react-multiple-elements-without-wrapper

Turns out this isn't possible yet, I wrote about 2 workarounds here: https://www.wptutor.io/web/js/react-multiple-elements-without-wrapper

推荐答案

目前还没有办法在没有某种解决方法的情况下执行此操作,例如将所有内容包装在另一个组件中,因为它最终会导致底层的React代码尝试返回多个对象。

It's not currently possible to do this without some sort of workaround like wrapping everything in another component, since it ends up with the underlying React code trying to return multiple objects.

请参阅此活跃的Github问题对于未来版本的考虑正在考虑支持。

See this active Github issue where support for this is being considered for a future version though.

编辑:你现在可以使用React 16中的Fragments执行此操作,请参阅:
https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html

You can now do this with Fragments in React 16, see: https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html

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

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