TypeScript类组件转换报错:定义Props接口为何仍无效?
React类组件转TypeScript的两个报错原因及解决方法
为什么Props接口解决不了这两个问题?
你定义的SeeMoreProps接口只负责约束组件外部传入的属性,而wrapper是组件内部的实例ref属性,_handleResize是内部的方法绑定属性,这两个都属于组件内部状态/属性范畴,和Props完全无关,所以Props接口根本管不到它们,自然解决不了这类报错。TypeScript是静态类型检查,类里的所有实例属性都必须提前声明类型,否则TS会认为这些属性不存在于当前类的类型定义中。
问题1:this.wrapper = React.createRef()报错
原因:你没有在ShowMore类中声明wrapper这个属性的类型,TS不知道这个属性存在。
解决方法:在类内部先声明wrapper的类型,再在构造函数里赋值:
class ShowMore extends React.Component<SeeMoreProps> { // 声明ref属性的类型,根据实际元素调整(比如是div就用HTMLDivElement) wrapper: React.RefObject<HTMLDivElement>; constructor(props: SeeMoreProps) { super(props); this.wrapper = React.createRef(); } // ...其他代码 }
问题2:this._handleResize = () => this.handleResize报错
原因:同样是没在类中声明_handleResize的类型,另外你的写法有问题——这里应该是调用handleResize方法,而不是直接赋值函数引用(否则绑定后调用的是函数本身,不是执行)。
解决方法:先声明_handleResize的类型,再正确绑定方法:
class ShowMore extends React.Component<SeeMoreProps> { // 声明方法属性的类型 _handleResize: () => void; constructor(props: SeeMoreProps) { super(props); // 注意要加()执行handleResize this._handleResize = () => this.handleResize(); } handleResize() { // 你的resize逻辑代码 } // ...其他代码 }
或者更简洁的方式:直接在类里用箭头函数定义_handleResize,避免手动绑定:
class ShowMore extends React.Component<SeeMoreProps> { // 直接用箭头函数定义,自动绑定this,无需在构造函数里赋值 _handleResize = () => { this.handleResize(); }; handleResize() { // 你的resize逻辑代码 } // ...其他代码 }
完整示例代码
import React from 'react'; // 你的Props接口定义 interface SeeMoreProps { content: string; maxHeight?: number; } class ShowMore extends React.Component<SeeMoreProps> { wrapper: React.RefObject<HTMLDivElement>; _handleResize: () => void; constructor(props: SeeMoreProps) { super(props); this.wrapper = React.createRef(); this._handleResize = () => this.handleResize(); } handleResize() { // 示例resize逻辑:获取wrapper高度做处理 if (this.wrapper.current) { console.log('wrapper高度:', this.wrapper.current.offsetHeight); } } componentDidMount() { window.addEventListener('resize', this._handleResize); } componentWillUnmount() { window.removeEventListener('resize', this._handleResize); } render() { return ( <div ref={this.wrapper} style={{ maxHeight: this.props.maxHeight || 200, overflow: 'hidden' }}> {this.props.content} </div> ); } } export default ShowMore;
内容的提问来源于stack exchange,提问作者Khant Min Si Thu
相关产品推荐
相关产品推荐

