2017-02-24 7 views
0

Ich habe folgende Array:dynamische Rendering in React

const elements = [ 
    { 
     title: "foo" 
     section: <div>Foo <button onClick={sayHello}>Greet</button></div> 
    }, 
    { 
     title: "bar" 
     section: <div>Bar <button onClick={sayHello}>Greet</button></div> 
    } 
]; 

Ich möchte die Komponente mit so etwas wie machen:

const someSections = this.state.elements.map((item, i) => (
    <div key={i}> 
    {item.section} 
    </div> 
)); 

... 

render(){ 
    return (
     ... 
     <div> 
      {someSections} 
     </div> 
    ) 
} 

Aber ich kann sie nicht machen. Der Fehler ist:

Uncaught Error: objects are not valid as a React child

+0

item.section, nicht link.section in Ihrer Karte: D – Kornflexx

+0

Ihre Daten sollten wirklich nicht HTML enthalten, nur die Vorlagen –

Antwort

1

Überprüfen Sie die Arbeitslösung:

const data = [ 
 
    { 
 
     title: "foo", 
 
     section: <div>Foo <button>Greet</button></div> 
 
    }, 
 
    { 
 
     title: "bar", 
 
     section: <div>Bar <button>Greet</button></div> 
 
    } 
 
] 
 

 

 
class App extends React.Component{ 
 
    render(){ 
 
    return(
 
     <div> 
 
      { 
 
       data.map((item,i)=>{ 
 
        return <div key={i}>{item.section}</div> 
 
       }) 
 
      } 
 
     </div> 
 
    ) 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <App/>, 
 
    document.getElementById('app') 
 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<div id='app'></div>

1

normalerweise würden Sie etwas tun.

render(){ 
    let someSections = this.state.elements.map((item, i) => (
     <div key={i}> 
      {item.section} 
     </div> 
    )); 

    return (
     <div> 
      {someSections} 
     </div> 
    ) 
}