背景
在react+typescript编写代码的时候,提示类型“Readonly<{}>”上不存在属性“xxx”
这是因为state和props没有定义类型导致的。
解决办法
- 法一
给state和props都定义指定类型
import React, { Component } from 'react';
type StateType = {
username: string;
};
type propType = {
name: string;
[propName: string]: any;
};
interface User {
state: StateType;
props:propType
}
class User extends Component {
constructor(props: any) {
super(props);
this.state = {
username: '李四'
}
}
render() {
return (
<div>
<div className="title">用户名{this.state.username}</div>
<div className="title">用户名{this.props.name}</div>
</div>
)
}
}
export default User
法二:
React.Component改成React.Component<any, any>
但是不推荐这样,因为这样就失去了ts检测类型的意义
import React, { Component } from 'react';
export default class User extends Component<any, any> {
constructor(props: any) {
super(props);
console.log(props);
this.state = {
username: '李四'
}
}
render() {
return (
<div>
<div className="title">用户名{this.state.username}</div>
<div className="title">用户名{this.props.name}</div>
</div>
)
}
}
文章参考
https://www.cnblogs.com/llcdbk/p/13029996.html