React函数组件向类组件传Props报错,请求排查解决
React类组件Props无法识别的TypeScript解决方案
你的问题出在TypeScript的类型校验上——本地IDE用的是TS环境,而在线playground是纯JavaScript环境,所以会出现这种差异。TypeScript要求React类组件必须显式声明Props的类型,否则默认Props类型是空对象{},导致你传递的title、name等属性被判定为不存在。
具体修复步骤:
- 为每个类组件定义对应的Props接口,明确声明接受的属性类型
- 将接口作为泛型参数传给
React.Component
修改后的完整代码:
const testData = [ {name: "Dan Abramov", avatar_url: "https://avatars0.githubusercontent.com/u/810438?v=4", company: "@facebook"}, {name: "Sophie Alpert", avatar_url: "https://avatars2.githubusercontent.com/u/6820?v=4", company: "Humu"}, {name: "Sebastian Markbåge", avatar_url: "https://avatars2.githubusercontent.com/u/63648?v=4", company: "Facebook"}, ]; const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement ); // 定义App组件的Props类型 interface AppProps { title: string; } class App extends React.Component<AppProps> { render() { return ( <div> <div className="header">{this.props.title}</div> <CardList /> </div> ); } } root.render( <App title="The GitHub Cards App" /> ); const CardList = () => ( <div> {testData.map(profile => <Card {...profile}/>)} </div> ); // 定义Card组件的Props类型 interface CardProps { name: string; avatar_url: string; company: string; } class Card extends React.Component<CardProps> { render() { const profile = this.props; return ( <div className="github-profile"> <img src={profile.avatar_url} alt="Cant show "/> <div className="info" style={{verticalAlign:'top'}}> <div className="name" style={{fontSize:'125%'}}>{profile.name}</div> <div className="company">{profile.company}</div> </div> </div> ); } }
关键说明:
- 给
App组件添加AppProps接口后,TS就能识别title属性是合法的Props - 给
Card组件添加CardProps接口后,avatar_url、name、company这些属性的类型也会被TS认可 - 在线playground用的是纯JS,不需要类型声明,所以代码能正常运行,但TS环境下必须显式定义类型才能通过校验
内容的提问来源于stack exchange,提问作者Tauqir
相关产品推荐
相关产品推荐

