React TypeScript渲染组件时出现类型不兼容错误求助
React根据对象键渲染组件时的TypeScript类型错误
错误信息
Type 'FC<Boxprops> | ExoticComponent<{ children?: ReactNode; }>' is not assignable to type 'FC<Boxprops>'. Type 'ExoticComponent<{ children?: ReactNode; }>' is not assignable to type 'FunctionComponent<Boxprops>'.
相关代码
import "./styles.css"; import { BOX, Boxprops } from './box' import React from "react"; let obj = { component:'box' } export default function App() { const getComponnets = () => { let Component: React.FC<Boxprops> = obj.component === 'box' ? BOX : React.Fragment return <Component title="asd" /> } return ( <div className="App"> {getComponnets()} </div> ); }
问题原因
React.Fragment的类型是ExoticComponent<{ children?: ReactNode; }>,它不接收title这类自定义props,但你将它和需要Boxprops的BOX组件一同赋值给了类型为React.FC<Boxprops>的变量,两者类型不匹配导致报错。
解决方法
方法一:替换Fragment为无props的空组件
如果非box分支不需要渲染内容,直接返回空组件替代Fragment,确保类型匹配:
const getComponnets = () => { let Component: React.FC<Boxprops> = obj.component === 'box' ? BOX : () => null; return <Component title="asd" />; };
方法二:分支处理props传递
保留Fragment,但在渲染时区分组件类型,避免给Fragment传递不支持的props:
const getComponnets = () => { const Component = obj.component === 'box' ? BOX : React.Fragment; if (Component === React.Fragment) { return <Component />; } return <Component title="asd" />; };
方法三:类型断言(谨慎使用)
如果你能确保只有在component为'box'时才会传递props,可以用类型断言跳过类型检查:
const getComponnets = () => { let Component = (obj.component === 'box' ? BOX : React.Fragment) as React.FC<Boxprops>; return <Component title="asd" />; };
内容的提问来源于stack exchange,提问作者user5711656
相关产品推荐
相关产品推荐

