Expo从v48升级到v49后React 18与TypeScript的styled-components错误
Expo升级后styled-components的TypeScript类型错误问题
近期将Expo应用从v48升级至v49,同步把React从v16升级到v18。升级完成后,使用带有children属性的styled-components组件时触发TypeScript错误,查阅相关问题后仍无法解决。
代码示例
Row.tsx
import React from 'react'; import { View, ViewProps } from 'react-native'; import styled from 'styled-components/native'; interface Props extends ViewProps { children: React.ReactNode; } const StyledView = styled(View)<Props>` flex-direction: row; `; export const Row = ({ children, ...props }: Props) => { return <StyledView {...props}>{children}</StyledView>; };
MyComponent.tsx
import React from 'react'; import { View } from 'react-native'; import { Row } from '../components/custom-components'; const MyComponent = () => { return ( <Row> <View /> {/* 错误出现位置 */} </Row> ); };
即使将子元素换成<H1>,错误依然存在。
错误信息
Type 'Element' is not assignable to type 'ReactNode'. Property 'children' is missing in type 'Element' but required in type 'ReactPortal'.
依赖版本
{ "react-native": "0.72.6", "react": "18.2.0", "react-dom": "18.2.0", "typescript": "^5.1.3", "styled-components": "^5.3.5", "styled-system": "^5.1.5", "@types/styled-components": "5.1.26", "@types/styled-components-react-native": "^5.1.3", "@types/styled-system": "^5.1.16", "@types/react-dom": "~18.0.10", "@types/react": "18.2.38" }
解决方法
移除Props中显式定义的children:
ViewProps已经内置了children的类型定义(React 18中已适配ReactNode),无需重复声明。修改后的Row.tsx如下:import React from 'react'; import { View, ViewProps } from 'react-native'; import styled from 'styled-components/native'; type Props = ViewProps; const StyledView = styled(View)<Props>` flex-direction: row; `; export const Row = ({ children, ...props }: Props) => { return <StyledView {...props}>{children}</StyledView>; };调整children类型为可选:如果必须自定义Props,可将
children设为可选类型,避免和内置类型冲突:interface Props extends ViewProps { children?: React.ReactNode; }升级styled-components类型依赖:当前
@types/styled-components版本较旧,尝试升级到最新兼容版本,确保适配React 18的类型规范:npm install @types/styled-components@latest @types/styled-components-react-native@latest --save-dev
内容的提问来源于stack exchange,提问作者NicoleZ
相关产品推荐
相关产品推荐

