【问题标题】:Props not being passed when using custom document for styled components为样式化组件使用自定义文档时未传递道具
【发布时间】:2019-07-19 17:22:42
【问题描述】:

我正在尝试将样式化组件与 next.js 一起使用。我添加了 babel 插件并添加了自定义 _document.js。这一切似乎都很好。

但是,当我尝试在页面中使用 isomorphic-unfetchgetInitialProps 时,请求会返回数据,但它不会进入 Props。

对于_document.js,我使用的是next.js 站点here 中的代码,并且还尝试了与here 稍有不同的版本,我也曾在某些时候在next.js 文档站点上看到过。

我的测试页面是这样的(同样来自 next.js docs):

import styled from 'styled-components';
import fetch from 'isomorphic-unfetch';

export default class MyPage extends React.Component {
    static async getInitialProps({ req }) {
        const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
        return { userAgent }
    }

    render() {

            return (
                <div>
                  Hello World {this.props.userAgent}
                </div>
              )
    }
}

我还有一个_app.js,看起来像这样:

import App, { Container } from 'next/app';
import Page from '../components/Page';

class MyApp extends App {
  render() {
    const { Component } = this.props;

    return (
      <Container>
        <Page>
          <Component />
        </Page>
      </Container>
    );
  }
}

export default MyApp;

Page.js 只是有一些样式化的组件和一个带有如下组件的主题:

class Page extends Component {
    render() {
        return (
            <ThemeProvider theme={theme}>
                <StyledPage>
                    <GlobalStyle />
                    <Meta />
                    <Header />
                    {this.props.children}
                </StyledPage>
            </ThemeProvider>
        );
    }
}

export default Page;

我觉得这与新的 _document.js 或 _app.js 没有以某种方式传递道具有关。

显然我对 next.js 很陌生,所以如果它是愚蠢的,请道歉。与此同时,我将继续努力,以更好地了解正在发生的事情。因为这个项目我有一些时间压力,所以我想在这里并行询问。

非常感谢您提出的任何想法。

【问题讨论】:

  • 您可以尝试在App.js 中添加&lt;Page {...this.props}&gt; 以将道具从App.js 传递到Page.js
  • 是的,你绝对是正确的。我花了太长时间查看 _document.js 而不是 _app.js。感谢您的回复。
  • 不客气 :)

标签: javascript css reactjs styled-components next.js


【解决方案1】:

发布后不久,我解决了这个问题。我想在 SO 上发帖有助于理解这个问题。

基本上问题出在_app.js,而不是我最初预期的_document.js

我需要将pageProps 添加到_app.js 以便它们向下传播到页面:

import App, { Container } from 'next/app';
import Page from '../components/Page';

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>
        <Page>
          <Component {...pageProps} />
        </Page>
      </Container>
    );
  }
}

export default MyApp;

【讨论】:

    猜你喜欢
    • 2020-05-26
    • 2021-09-11
    • 2021-01-15
    • 2020-10-28
    • 1970-01-01
    • 2018-05-13
    • 2021-06-29
    • 2017-08-17
    • 2019-11-11
    相关资源
    最近更新 更多