ReactJS - 从映射构造html

时间:2015-10-14 12:07:40

标签: reactjs

  

我找到了我想要的解决方案并且有效,见下文......

我知道我做了一些愚蠢的事情,但我今天早上有精神障碍,并会感激一些帮助。我试图从映射构造html:

在我的渲染中:

< ul>
  { arryItems.map(this.foo.bind(this)) }
< /ul>

通话功能:

foo(arry, i) {
 let result = '';

 if (arry.children != undefined && arry.children.length > 0) { 
    result= ( 
             <div key= {i}>{arry.name}
               {arry.children.map(function(child, ix){
                 <p key= {ix}>{child.name}</p>
               })}
             </div>
            )
  } else {
         result = (<div>{arry.name}</div>)
  }

   return result;
};

我正在尝试返回html。

  

虽然我没有收到任何错误,但&lt; p为H. {child.name}&LT; / p为H.不在返回html结果中。

任何人都可以用我的想法指出什么是如此明显的明显,我无法弄清楚这一点?

2 个答案:

答案 0 :(得分:1)

所以你想将组件渲染为html字符串? React使用renderToString执行此操作。 e.g:

var Task = React.createClass({
  render() {
    return (
      <li>{this.props.task.text}</li>
    );
  }
});

var Tasks = React.createClass({
  getTasks() {
    return [
      { _id: 1, text: 'This is task 1' },
      { _id: 2, text: 'This is task 2' },
      { _id: 3, text: 'This is task 3' }
    ];
  },

  renderTasks() {
    return this.getTasks().map(task => {
      return <Task key={task._id} task={task} />;
    });
  },

  render() {
    return (
        <ul>
          {this.renderTasks()}
        </ul>
    );
  }
});

var html = ReactDOMServer.renderToString(Tasks);

请注意,自0.14以来,此方法已拆分为react-dom/server包,早期版本只在react包中。

答案 1 :(得分:0)

  

我很欣赏Dominic的帮助,但我更喜欢我的解决方案,因为它很紧凑并且会检查是否没有孩子:

 foo(arry, index) {
    let children = this.getChildren(arry)
    return (
        <div key={index}>{arry.name}
            { children }
        </div>
    )
}

getChildren(arry){
    let result = [];
    if(arry.children != undefined && arry.children.length > 0){
         arry.children.map(function(child, ix){
             result.push(<p key={ix}>{child.name}</p>)
         })
    }
    return result;
}

render() {
   return (
       <section>
         { arryItems.map(this.foo.bind(this)) }
       </section>
   );
}