我已经被困了一段时间,试图弄清楚我在这里做错了什么,我觉得我已经尝试了我找到的所有解决方案,但它不起作用。为了描述正在发生的事情,我制作了最简单的组件来展示正在发生的事情。
这是我的主题
export default const theme = {
colors: {
white: '#FFFFFF',
black: '#000',
lightGray: '#f0f2f1',
darkGray: '#909190',
primaryColor: '#007772',
secondaryColor: '#0775BC',
textColor: '#231F20',
lightPrimary: '#DBFFFF',
red: '#B80F0A',
primaryHalf: '#7FBAB8',
},
font: {
family: 'Nunito-Regular',
},
};
这是我的组件
import React from 'react';
import styled from 'styled-components/native';
const Wrapper = styled.View`
background-color: ${(props) => props.theme.colors.white};
`;
const TestSimpleComponent: React.FC = ({ children }) => {
return <Wrapper>{children}</Wrapper>;
};
export default TestSimpleComponent;
很简单,只是用来自主题的白色背景包裹一些东西。
最后,这是我的简单测试
import React from 'react';
import { Text } from 'react-native';
import { render } from '@testing-library/react-native';
import TestSimpleComponent from './TestSimpleComponent';
import { ThemeProvider } from 'styled-components';
import theme from '../../themes/primary';
describe('TestSimpleComponent', () => {
it('displays correct children', () => {
const { queryByText } = render(
<ThemeProvider theme={theme}>
<TestSimpleComponent>
<Text>Test</Text>
</TestSimpleComponent>
</ThemeProvider>,
);
expect(queryByText('Test')).not.toBeNull();
});
});
这是抛出的错误。基本上是说主题提供者出于某种我似乎无法弄清楚的原因没有将主题传递给组件。
TypeError: Cannot read property 'white' of undefined
3 |
4 | const Wrapper = styled.View`
> 5 | background-color: ${(props) => props.theme.colors.white};
| ^
6 | `;
7 |
8 | const TestSimpleComponent: React.FC = ({ children }) => {
我觉得我已经尝试了我在这里找到的几乎所有东西,人们遇到了同样的问题,但似乎没有任何效果。唯一有效的是我手动将主题传递给 Wrapper,这不是一个可行的解决方案,因为我有一个大型应用程序,它在各处的样式组件中使用主题。
之前我使用颜色文件时,我所有的测试都通过了,但是一旦我将其切换为主题,一切都失败了
我也尝试了所有引用 here 的东西。
有人知道我可能做错了什么吗?
答案 0 :(得分:0)
以防万一有人想知道答案是什么。 我遇到的问题的解决方案正在改变
import { ThemeProvider } from 'styled-components';
到
import { ThemeProvider } from 'styled-components/native';