我有以下数组:
const elements = [
{
title: "foo"
section: <div>Foo <button onClick={sayHello}>Greet</button></div>
},
{
title: "bar"
section: <div>Bar <button onClick={sayHello}>Greet</button></div>
}
];
我想用以下内容渲染组件:
const someSections = this.state.elements.map((item, i) => (
<div key={i}>
{item.section}
</div>
));
...
render(){
return (
...
<div>
{someSections}
</div>
)
}
但我无法渲染它们。错误是:
Uncaught Error: objects are not valid as a React child
答案 0 :(得分:1)
检查工作解决方案:
i
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')
);
答案 1 :(得分:1)
render(){
let someSections = this.state.elements.map((item, i) => (
<div key={i}>
{item.section}
</div>
));
return (
<div>
{someSections}
</div>
)
}