React中的动态渲染

时间:2017-02-24 14:13:38

标签: javascript reactjs

我有以下数组:

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

2 个答案:

答案 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>
    )
}