我正在尝试从一个辅助方法返回多个React元素。我可以简单地通过移动一些代码来解决它,但是我想知道是否有一种更干净的方法来解决它。我有一个返回该render方法一部分的方法,并且该函数需要同时返回一个React元素和一些文本。通过一个例子更清楚:
render
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元素。使用这样的辅助方法会触发警告,而修复警告(通过添加键)会使代码过于复杂。有没有一种干净的方法可以执行此操作而不触发警告?
编辑:
另一个用例:
render() { return ( <div> {user ? <h2>{user.name}</h2> <p>{user.info}</p> : <p>User not found</p>} </div> ); }
编辑2:
事实证明这还不可能,我在这里写了两种解决方法:https://www.wptutor.io/web/js/react-multiple-elements- without-wrapper
如果没有某种解决方法(例如将所有内容包装在另一个组件中),当前不可能做到这一点,因为它最终会导致底层的React代码尝试返回多个对象。
请参阅这个活跃的Github问题,尽管正在考虑为将来的版本提供支持。
编辑:您现在 可以 在React 16中使用片段执行此操作,请参阅:https: //reactjs.org/blog/2017/11/28/react-v16.2.0-fragment- support.html