在没有包装器元素的方法中返回多个React元素

编程入门 行业动态 更新时间:2024-10-25 12:21:11
本文介绍了在没有包装器元素的方法中返回多个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个解决方法: www.wptutor.io/web/js/react-multiple-elements-without-wrapper

Turns out this isn't possible yet, I wrote about 2 workarounds here: 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执行此操作,请参阅: reactjs/blog/2017/11/28/react-v16.2.0-fragment-support.html

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

更多推荐

在没有包装器元素的方法中返回多个React元素

本文发布于:2023-10-04 02:40:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467106.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   多个   方法   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!