2017-10-07 135 views
1

我有一个React组件返回一个HTML表格。React组件返回原始HTML

调用使用:<Options list={item} />

这是返回表中的功能组件:

const Options = (props) => { 

let table = ` 
<table className="table table-striped table-hover "> 
     <thead> 
      <tr> 
      <th>#</th> 
      <th>Option</th> 
      <th>Votes</th> 
     </tr> 
     </thead> 
     <tbody> 
` 

for (let i = 0; i < props.list.options.length; i++){ 
    table += `<tr> 
    <td>${i+1}</td> 
    <td>${props.list.options[i].option}</td> 
    <td>${props.list.options[i].vote}</td> 
    </tr> 
    ` 
} 

table += `</tbody></table>` 
return table; 
} 

但我在屏幕上看到的是:

enter image description here

怎么来的HTML没有被浏览器渲染?

+1

这是因为你实际上是返回一个字符串。 –

+0

我鼓励你[学习JSX](https://reactjs.org/docs/jsx-in-depth.html),和一个HTML字符串的区别,这就是你现在使用的。 –

回答

2

您正在返回的字符串。你应该这样做

const Options = (props) => { 

    let table = 
     (<table className="table table-striped table-hover "> 
      <thead> 
      <tr> 
       <th>#</th> 
       <th>Option</th> 
       <th>Votes</th> 
      </tr> 
      </thead> 
      <tbody> 
      {props.list.options.map((op, i) => { 
       return (
       <tr key={i}> 
        <td>{i+1}</td> 
        <td>{op.option}</td> 
        <td>{op.vote}</td> 
       </tr> 
       ) 
      })}; 
      </tbody> 
     </table>); 

    return table; 
    } 
+0

您缺少'key'。 –

+0

@ArupRakshit谢谢指出 –

0

如果你使用JSX像下面,它会呈现为HTML:

return <div> {table} </div> 

但我会写这个功能组件为:

const Options = props => { 
    const tableBody = props.list.options.map((obj, i) => (
    <tr key={i}> 
     <td>{i + 1}</td> 
     <td>{obj.option}</td> 
     <td>{obj.vote}</td> 
    </tr> 
)); 

    return (
    <table className="table table-striped table-hover"> 
     <thead> 
     <tr> 
      <th>#</th> 
      <th>Option</th> 
      <th>Votes</th> 
     </tr> 
     </thead> 
     <tbody>{tableBody}</tbody> 
    </table> 
); 
};