javascript - 如何将道具传递给在 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,现在它变成了一个返回组件的函数,所以我不能像过去那样使用它。我正在努力理解如何做到这一点。
解决方案
好吧,它就在错误中。Theme.Light
是一个函数,而不是一个组件,这意味着使它工作的方法是使用Theme.Light({ brand: 'BrandName' })
.
这可能会有所帮助:
const lightCmp = Theme.Light({ brand: 'Adidas' });
const App = () => (
<lightCmp>
<SpecialComponent />
</lightCmp>
);
编辑:
它之前工作的原因是因为Light
您分配了theme()
一个组件的返回,在您的新版本中,您需要先实例化该函数。基本上,您通过一个额外的步骤来做同样的事情。
另一种解决方案可能是有一个useTheme({ brand })
返回 HoC 组件的钩子。
推荐阅读
- powershell - 如何将成员添加到 ForEach 循环中对象的现有属性?
- r - 在 R 中使用 lapply 从二项式分布创建样本时出错
- c# - .net 核心依赖注入“IMyService”是一种在给定上下文中无效的类型
- python - 未按特定顺序传递 lambda 函数中的参数时出错
- postgresql - 使用函数计算gps位置和postgis地理值之间的距离?
- python - 我如何从 steam api 获取统计信息
- javascript - 如何优化块的显示?
- python - 我在为 python 安装 pdftotext 时遇到困难
- python - 如何返回字节数组以便在浏览器中以 zip 文件的形式下载?
- java - 如何解决 osgi.wiring.package=javax.jms)(version>=1.1.0)(!(version>=2.0.0) 问题?