我有一个简单的组件:
import React, { FunctionComponent } from 'react';
import { ViewStyle, StyleProp, StyleSheet } from 'react-native';
import {
RoundedCardBackground,
} from './index';
type RoundedCardProps = {
style?: StyleProp<ViewStyle>;
shadow?: boolean;
};
const RoundedCard: FunctionComponent<RoundedCardProps> = ({
style,
children,
shadow,
}) => {
let shadowStyle = shadow ? styles.shadow : undefined;
return (
<RoundedCardBackground style={[shadowStyle]}>
{children}
</RoundedCardBackground>
);
};
const styles = StyleSheet.create({
shadow: {
elevation: 2,
shadowColor: '#000000',
shadowOffset: {
width: 0,
height: 3,
},
shadowRadius: 10,
shadowOpacity: 0.05,
},
});
export default RoundedCard;
我正在尝试测试一个简单的功能,但我收到了来自 styled-components 主题的错误。
这是我的测试:
import React from 'react';
import { Text } from '/components/atoms';
import { render } from '/utilities/testUtils';
import theme from '../../themes/primary';
import RoundedCard from './RoundedCard';
describe('RoundedCard', () => {
it('displays correct children', () => {
const { queryByText } = render(
<ThemeProvider theme={theme}>
<RoundedCard>
<Text>Test</Text>
</RoundedCard>,
</ThemeProvider>
);
expect(queryByText('Test')).not.toBeNull();
});
});
这是我得到的错误:
TypeError: Cannot read property 'white' of undefined
79 | export const RoundedCardBackground = styled.View`
80 | flex-shrink: 1;
> 81 | background-color: ${(props) => props.theme.colors.white};
| ^
82 | border-radius: 6px;
83 | overflow: hidden;
84 | `;
有什么我想念的吗?我认为将组件包装在 ThemeProvider 中可以解决问题,但仍然会出现错误。
仅供参考,这是引发错误的样式组件
export const RoundedCardBackground = styled.View`
flex-shrink: 1;
background-color: ${(props) => props.theme.colors.white};
border-radius: 6px;
overflow: hidden;
`;