首页 > 解决方案 > 如何将道具传递给在 React 中返回组件的导入函数?

问题描述

我试图将一个参数传递回我的组件库,该组件库作为依赖项导入到父应用程序中,但我不完全确定如何实现这一点,我希望有人能告诉我我做错了什么。这个想法是,在客户登录时,我们将确定他们使用哪个品牌并切换应该使用的主题(我添加了一个简化的示例,呈现 a SpecialComponent

目前,我的组件库中有一个 Theme 对象,它返回一个 ThemeProvider 中包装的 Theme 组件。在我尝试扩展主题对象的概念并添加品牌概念之前,这一直很好。

这是我的Theme.js

import React from 'react';
import PropTypes from 'prop-types';
import { ThemeProvider } from 'styled-components';

export const theme = config => {
  const Theme = (props) => (
    <ThemeProvider theme={config}>
      {props.children}
    </ThemeProvider>
  );
  Theme.propTypes = {
    children: PropTypes.node.isRequired
  };
  return Theme;
};

const LightThemes = {
    Adidas: {
        name: 'Light',
        variant: 'white',
        background: 'red',
        color: 'green',
        textColor: 'white'
    },
    Nike: {
        name: 'Light',
        variant: 'red',
        background: 'black',
        color: 'yellow',
        textColor: 'black'
    }
};

const Light = ({ brand }) => theme(LightThemes[brand]);

const Theme = {
  Light
};

export default Theme;

这是我在我的应用程序中调用它的方式:

import React from 'react';
import {
  SpecialComponent,
  Theme
} from '@my-component-library';

const App = () => (
  <Theme.Light brand={'Adidas'}>
    <SpecialComponent />
  </Theme.Light>
);

export default App;

如您所见,我正在尝试将字符串传递Adidas给,<Theme.Light>但是这不起作用,并且我得到一个错误回复说Warning: Functions are not valid as a React child..

在我添加品牌概念之前,我的 Theme.js 看起来像这样,并且运行良好:

import React from 'react';
import PropTypes from 'prop-types';
import { ThemeProvider } from 'styled-components';

export const theme = config => {
  const Theme = (props) => (
    <ThemeProvider theme={config}>
      {props.children}
    </ThemeProvider>
  );
  Theme.propTypes = {
    children: PropTypes.node.isRequired
  };
  return Theme;
};

const LightThemes = {
    name: 'Light',
    variant: 'white',
    background: 'red',
    color: 'green',
    textColor: 'white'
};

const Light = theme(LightThemes);

const Theme = {
  Light
};

export default Theme;

我相信这是因为以前我有一个 HOC,现在它变成了一个返回组件的函数,所以我不能像过去那样使用它。我正在努力理解如何做到这一点。

标签: javascriptreactjs

解决方案


好吧,它就在错误中。Theme.Light是一个函数,而不是一个组件,这意味着使它工作的方法是使用Theme.Light({ brand: 'BrandName' }).

这可能会有所帮助:

const lightCmp = Theme.Light({ brand: 'Adidas' });

const App = () => (
  <lightCmp>
    <SpecialComponent />
  </lightCmp>
);

编辑:

它之前工作的原因是因为Light您分配了theme()一个组件的返回,在您的新版本中,您需要先实例化该函数。基本上,您通过一个额外的步骤来做同样的事情。

另一种解决方案可能是有一个useTheme({ brand })返回 HoC 组件的钩子。


推荐阅读