2017-10-07 132 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> 
); 
};