javascript - 对样式化组件使用自定义文档时未传递 Prop

标签 javascript css reactjs styled-components next.js

我正在尝试将带样式的组件与 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 没有以某种方式传递 Prop 有关。

很明显,我对 next.js 还很陌生,如果有什么愚蠢的地方,我深表歉意。与此同时,我会继续努力以更好地了解正在发生的事情。我想在这里并行提问,因为我在这个元素上有一些时间压力。

非常感谢您的任何想法。

最佳答案

发布后不久,我解决了这个问题。我想在 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;

关于javascript - 对样式化组件使用自定义文档时未传递 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54880893/

相关文章:

javascript - 如何使行悬停覆盖数据表中的选择?

html - CSS 问题 - 页脚太长?

javascript - 与react-router-dom 4 react - 无法读取未定义的属性 'params'

javascript - Redux-form:在模式弹出时如何从 API 调用加载值(编辑模式)到表单?

javascript - reactjs组件中if(x)和if(x==true)的区别

javascript - Bootstrap select searchable 在另一个下拉列表中选择

javascript - 对一个元素调用 .each

javascript - 如何将状态推送到包含特定项目的数组?

javascript - 尝试使用 chrome.downloads(由于某种原因未定义)

javascript - 带有流畅背景图像的光滑 slider 空白空间