NextJS-在自定义应用中将状态作为道具传递给孩子

时间:2019-02-17 20:55:29

标签: reactjs next.js

我有这个./pages/_app.js from the official docs

import App, { Container } from 'next/app'

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {}

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return { pageProps }
  }

  render () {
    const { Component, pageProps } = this.props

    return (
      <Container>
        <Component {...pageProps} />
      </Container>
    )
  }
}

export default MyApp

我想将状态从MyApp传递到它呈现的每个页面,但不知道如何。我尝试过:

const childProps = {
  ...
}

<Container>
  <Component {...childProps} />
</Container>

并出现错误:

React.Children.only expected to receive a single React element child.

2 个答案:

答案 0 :(得分:0)

罪魁祸首是

<Link>
  <Icon />
  text
</Link>
呈现页面中的

(不是_app.js)。 链接有两个孩子(react-router链接的残余),而不是一个。

答案 1 :(得分:0)

通过常规道具时传递您想要的东西

<section class="blog">
  <h2>Just relax <span>&</span> <br>Let us do the heavy lifting</h2>
  <p>Proin iaculis purus consequat sem cure digni ssim. Donec porttitora entum suscipit aenean rhoncus posuere odio in tincidunt.</p>
  <ul class="benefits-list">
    <li class="benefits-element">Initial Setup & Customizations</li>
    <li class="benefits-element">Regular Updates</li>
    <li class="benefits-element">Round The Clock Support</li>
  </ul>
  <button class="button-main">Learn more</button>
</section>

例如:这是我将MobileDetect道具传递给应用程序中每个组件的方式:

<Component whatyouwant={propsyouwant} />