如何在 React 中使用箭头函数定义为常量的嵌套组件?

How to use nested components defined as constant with arrow functions in React?

如果我从布局中注释掉 {children},这将按预期工作。 否则,错误

index.js Invariant Violation: Objects are not valid as a React child (found: object with keys {children})

为什么?

layout.js

const Layout = (children) => (<div>
  <Header />
  {children}
</div>)

export default Layout

index.js(根组件)

const IndexPage = () => (
  <Layout>
    <h1>Hi people</h1>
  </Layout>
)

export default IndexPage
(children) =>

不管你怎么称呼它,这是整个道具 object,而不仅仅是 children。要么使用解构来选择 children 道具:

({ children }) =>

或显式访问 props.children:

(props) => (
  <div>
    <Header />
    {props.children}
  </div>
)