reactjs意外的标记“/”

时间:2015-01-02 17:13:41

标签: javascript reactjs

您好我试图动态渲染React组件:

render: function() {
    return (
        <form  {...this.props}>
            <div className={'row'}>
                {this.props.fields.map(function(field, index){
                    if (index != 0 &&index%3==0) {
                        return (
                            </div><div className={'row'}>
                            <div className={'col-sm-4'}>
                                ...
                            </div>
                        )
                    } else{
                        return (
                            <div className={'col-sm-4'}>
                                ...
                            </div>
                        )
                    }
                })}
            </div>
        </form>
    );
}

但我收到此错误&#34;解析错误:第17行:解析文件时出现意外的令牌...&#34;

我文件中的第17行是</div><div className={'row'}>

还有另一种方法吗?是否可以将所有重复的代码放在变量中?

Obs:我使用的是browserify(7.0.x)和reactfy(0.17.1)

1 个答案:

答案 0 :(得分:0)

为了形式化FakeRainBrigand描述的正确答案并在上面的评论中由dirkk详细阐述,这里是修改了render修复了无效的HTML:

render: function() {
  return (
    <form  {...this.props}>
      <div className={'row'}>
        {
          this.props.fields.map(function(field, index) {
            if (index !== 0 && index % 3 === 0) {
              return (
                <div className={'row'}>
                  <div className={'col-sm-4'}>
                    {/* Whatever else each field is supposed to do if the index isn't zero but is divisible by three */}
                  </div>
                </div>
              )
            } else {
              return (
                <div className={'col-sm-4'}>
                  {/* Whatever else each field is supposed to do if the index is zero or isn't divisible by three */}
                </div>
              )
            }
          })
        }
      </div>
    </form>
  );
}

问题发生在if块中,其中(带有次要代码格式更新)最初看起来像这样:

if (index !== 0 && index % 3 === 0) {
  return (
    </div>
    <div className={'row'}>
      <div className={'col-sm-4'}>
        {/* ... */}
      </div>
  )
}

块开头的</div>是无效的HTML,因为它与之前的<div>没有关联 - 您无法关闭尚未打开的标记。但是,删除前导</div>无法解决问题:通过修复缩进,很明显</div>可能会在此块的末尾,div班级row永远不会关闭。此块的更正版本如下所示:

if (index !== 0 && index % 3 === 0) {
  return (
    <div className={'row'}>
      <div className={'col-sm-4'}>
        {/* Whatever else each field is supposed to do if the index isn't zero but is divisible by three */}
      </div>
    </div>
  )
}