如何使用 map 和 join 来渲染 react 组件? [英] How to render react components by using map and join?

查看:42
本文介绍了如何使用 map 和 join 来渲染 react 组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件将显示字符串数组.代码如下所示:

React.createClass({使成为() {<div>this.props.data.map(t => <span>t</span>)

}})

它工作得很好.即如果 props.data = ['tom', 'jason', 'chris'],页面中的渲染结果将是 tomjasonchris.

然后,我想用逗号连接所有的名字,所以我把代码改成:

this.props.data.map(t => t).join(', ')

但是渲染出来的结果是[Object], [Object], [Object].

我不知道如何将对象解释为要渲染的反应组件.有什么建议吗?

解决方案

一个简单的解决方案是使用 reduce() 没有第二个参数并且不传播之前的结果:

class List 扩展 React.Component {使成为() {<div>{this.props.data.map(t => <span>{t}</span>).reduce((prev, curr) => [prev, ', ', curr])}

}}

如果没有第二个参数,reduce()从索引 1 开始 而不是 0,React 对嵌套数组非常满意.

正如评论中所说,您只想将它​​用于至少包含一项的数组,因为没有第二个参数的 reduce() 将抛出一个空数组.通常,这应该不是问题,因为无论如何您都希望显示一条自定义消息,说明空数组的这是空的".

Typescript 更新

您可以在 Typescript 中使用它(没有类型不安全的 any)和 .map() 上的 React.ReactNode 类型参数:

class List 扩展 React.Component {使成为() {<div>{this.props.data.map(t => {t}).reduce((prev, curr) => [prev, ', ', curr])}

}}

I have one component which is going to display Array of String. The code looks like this:

React.createClass({
  render() {
     <div>
        this.props.data.map(t => <span>t</span>)
     </div>
  }
})

It is working perfectly fine. i.e. if props.data = ['tom', 'jason', 'chris'], the rendered result in the page would be tomjasonchris.

Then, I want to join all the names by using comma, so I change the code to:

this.props.data.map(t => <span>t</span>).join(', ')

However, the rendered result is [Object], [Object], [Object].

I don't know how to interpret object to become react components to be rendered. Any suggestion?

解决方案

A simple solution is to use reduce() without second argument and without spreading the previous result:

class List extends React.Component {
  render() {
     <div>
        {this.props.data
          .map(t => <span>{t}</span>)
          .reduce((prev, curr) => [prev, ', ', curr])}
     </div>
  }
}

Without second argument, reduce() will start at index 1 instead of 0, and React is perfectly happy with nested arrays.

As said in the comments, you want to only use this for arrays with at least one item, because reduce() without second argument will throw with an empty array. Normally this should not be a problem, since you want to display a custom message saying something like 'this is empty' for empty arrays anyway.

Update for Typescript

You can use this in Typescript (without type-unsafe any) with a React.ReactNode type parameter on .map():

class List extends React.Component {
  render() {
     <div>
        {this.props.data
          .map<React.ReactNode>(t => <span>{t}</span>)
          .reduce((prev, curr) => [prev, ', ', curr])}
     </div>
  }
}

这篇关于如何使用 map 和 join 来渲染 react 组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆