我从网页上复制了一个组件。
是这样的
export default class ShowMore extends React.PureComponent {
constructor(props) { //ERROR HERE
super(props);
this.wrapper = React.createRef(); //ERROR HERE
this.state = {
expand: false,
expandable: true,
height: '0px',
mounted: false,
};
this._handleResize = () => this.handleResize; //ERROR HERE
}
你可以看到这不是一个typescript代码
所以我试着把它转换成typescript但是它仍然给我错误
我有一些类组件的经验,但我没有typescript && class component
的经验,所以我现在很困惑。
根据我的理解,只要我给type
或interface
到props
,错误应该消失,但它没有,这里是更新的代码。
interface SeeMoreProps {
wrapper: any;
handleResize: any;
}
export default class ShowMore extends React.PureComponent {
constructor(props: SeeMoreProps) { //This error goes away
super(props);
this.wrapper = React.createRef(); // Error(Property 'wrapper' does not exist on type 'ShowMore')
this.state = {
expand: false,
expandable: true,
height: '0px',
mounted: false,
};
this._handleResize = () => this.handleResize; //Property '_handleResize' does not exist on type 'ShowMore'. Did you mean 'handleResize'?
}
有人可以帮助解释为什么我的界面不工作在这种情况下?
this.wrapper
应该在类组件的作用域中。
下面是更新后的代码:
interface SeeMoreProps {
wrapper: any;
handleResize: any;
}
export default class ShowMore extends React.PureComponent {
//This is the scope of the class component
wrapper: unknown;
_handleResize: unknown;
constructor(props: SeeMoreProps) {
super(props);
this.wrapper = React.createRef();
this.state = {
expand: false,
expandable: true,
height: '0px',
mounted: false,
};
this._handleResize = () => props.handleResize; //you need to pass
handleResize from props.handleResize;
}