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

问题描述 投票:0回答:1

如果我注释出 {children}从Layout中,这工作是预期的,否则,错误。

index.js 违反不变性。对象作为React子对象无效(发现:带键{children}的对象)

为什么?

layout.js

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

export default Layout

索引.js (根组件)

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

export default IndexPage
reactjs arrow-functions
1个回答
4
投票
(children) =>

尽管你叫它什么,但这是整个道具对象,而不仅仅是子对象。要么使用destructuring来挑选子代道具。

({ children }) =>

或者明确地访问props.children

(props) => (
  <div>
    <Header />
    {props.children}
  </div>
)
© www.soinside.com 2019 - 2024. All rights reserved.