2017-10-07 2 views
1

J'ai un composant React qui retourne un tableau HTML.Composant React retournant HTML brut

Invoqué en utilisant: <Options list={item} />

C'est le composant fonctionnel qui retourne la table:

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; 
} 

Mais ce que je vois à l'écran est:

enter image description here

Comment se fait le HTML n'est pas rendu par le navigateur?

+1

C'est parce que vous êtes en train de retourner une chaîne. –

+0

Je vous encourage à [en apprendre davantage sur JSX] (https://reactjs.org/docs/jsx-in-depth.html), et la différence à une chaîne de HTML, qui est ce que vous utilisez dès maintenant . –

Répondre

2

Vous retournerez chaîne. Vous devriez le faire comme ceci

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

Il vous manque 'key'. –

+0

@ArupRakshit Merci d'avoir signalé –

0

Si vous utilisez JSX comme ci-dessous, il sera rendu HTML:

return <div> {table} </div> 

Mais j'écrirait cette composante fonctionnelle:

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> 
); 
};