使用Reactjs将字符串数组转换为HTML

时间:2017-06-02 07:10:36

标签: reactjs

任何人都可以帮助我以正确的方式迭代一个字符串数组,然后使用Reactjs将其放在段落标记中吗?

该数组看起来像:

names = [ "James", "Susan", "Frank" ];

这是我的反应组件“Riders”(我已添加评论以获取有关我正在尝试做的事情):

import React from 'react';

import { Drivers } from '../api/drivers';

// The 'this.props.names' contains an array of names: ["John", "Susan", "John"].
// How would I iterate over the array, pull the names from this array, and then
// have those names rendered in a paragraph tag in a manner like:
// <p>John - Susan - John</p>

// So far I've attempted using template strings and the braces, {} , javascript
// injection. Doing this renders an empty paragraph. Please let know of the proper
// way to complete this task. Any help would be greatly appreciated. :)

export default class Riders extends React.Component {
  renderNames() {
    let empty = ``
    let names = this.props.names;
    let namesLength = names.length;
    for (var i = 0; i < namesLength; i++) {
      empty[i] = empty + `-` + ` ${empty[i]}`
    }
    return empty;
  }
  render() {
    return (
      <div>
        <p>{this.renderNames}</p>
      </div>
    );
  }
}

4 个答案:

答案 0 :(得分:2)

您的代码中存在一些错误。

首先,渲染时需要调用renderNames

<p>{this.renderNames()}</p>

然后renderNames实施不正确。

  1. empty是一个在js中不可变的字符串。你不能使用索引empty[i] = something
  2. 来改变一个
  3. 您应该检查当前元素不是第一个。因为您不想在第一个元素之前插入分隔符
  4. 整个循环是多余的。有一个特殊的方法join来连接给定分隔符的字符串数组。
  5. 所以renderNames可以简单为return this.props.names.join(' - ')

答案 1 :(得分:0)

所以这个现在有效!这是@Yury建议的Join方法的实现:

select CONCAT(LAST_DAY(NOW() - INTERVAL 1 MONTH), ' 23:59:59');

参考“Join()”方法:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join?v=control

答案 2 :(得分:-1)

查看JS .map方法https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map?v=control

你可以这样做:

let returnString = "";
this.props.names.map((item) => {
   //TODO: add something to check if it's the last item
   returnString += item + " - "
})

答案 3 :(得分:-1)

如上所示,您应该使用Error Code: 1242. Subquery returns more than 1 row 。请查看以下示例

{this.renderNames()}