React TypeScript组件传index属性报类型不匹配错误如何解决?
问题原因
该报错和props只读特性无关,根本原因是你没有为TypeScript声明React组件允许接收的props类型。
TypeScript环境下的React.Component是带泛型参数的,第一个泛型位就是props的类型定义,如果你没有显式传入该类型,TS会默认组件的props类型为空对象{},此时你给组件传递自定义的index属性,就会触发类型校验报错,提示该属性不存在于允许的props列表中。
你之前在constructor中写的props: any只是绕开了组件内部使用props时的类型校验,并不会修改组件对外暴露的props类型定义,所以无法解决外层调用时的传参报错。
修复步骤
- 先定义
NewsFeedItem组件的props类型
interface NewsFeedItemProps { index: number; // 后续新增props可直接在该接口中扩展 }
- 改造
NewsFeedItem组件,将定义好的props类型传入React.Component泛型
class NewsFeedItem extends React.Component<NewsFeedItemProps> { // 无额外初始化逻辑可以直接删除constructor,TS会自动处理props注入 render() { const theIndex = this.props.index return ( <span className="newsFeedItem"> test {theIndex} </span> ); } }
补充说明
- 如果props有可选参数,可在类型定义时加
?标记,比如index?: number - 其余组件如果后续需要接收自定义props,都可以按照同样的逻辑:先定义props接口,再将接口传入
React.Component的第一个泛型位即可
内容的提问来源于stack exchange,提问作者SomethingsGottaGive
相关产品推荐
相关产品推荐

