作为引用,我使用的是 React 16.9.0
和 Typescript 3.6.3
。
关于this tutorial ,他们建议不要在我的 react 类中定义实例属性:
Just don’t. Storing values on the instance of a component is doing this:
var React = require('react/addons'); class ArbitraryWidget extends React.Component { // ... constructor () { this.derp = 'something'; } handleClick () { this.derp = 'somethingElse'; } render () { var something = this.derp; // ... } }
This is particularly bad, not only because you’re breaking the obvious convention of storing state on this.state, but because render won’t automatically trigger when this.derp is updated.
但就我而言,我的类具有不影响组件状态的属性,然后,我可以将它们添加为实例属性,没有任何问题。
但是,我并没有考虑 Typescript 的攻击。如果您安装 Create React App
并创建 Typescript 项目,则可以添加以下最小示例来重现问题:
import React from 'react';
import './App.css';
interface AppProps {
}
interface AppState {
}
class App extends React.Component<AppProps, AppState>
{
constructor(props: AppProps) {
super(props);
this.var = 10;
this.state = {
};
}
render() {
return (
<div>
Hi!
</div>
)
}
}
export default App;
这将导致 Typescript 抛出错误:
/myfiles/src/App.tsx
TypeScript error in /myfiles/src/App.tsx(15,10):
Property 'var' does not exist on type 'App'. TS2339
13 | super(props);
14 |
> 15 | this.var = 10;
| ^
16 | this.state = {
17 | };
18 | }
添加其中之一:
interface AppProps {
var: any;
}
interface AppState {
var: any;
}
不起作用,Typescript 仍然不理解 var
是组件的属性,而不是 this.props
或 this.state 的属性
.
更新
根据答案中的建议,我尝试了以下操作:
private var: number;
但是现在,Typescript 抛出另一个错误:
Property 'var' is missing in type '{}' but required in type 'Readonly<AppState>'. TS2741
18 |
19 | this.var = 10;
> 20 | this.state = {
| ^
21 | };
22 | }
23 |
如果我删除 this.state = {}
,它仍然会抛出该错误:
Property 'var' is missing in type '{}' but required in type 'Readonly<AppProps>'. TS2741
5 | import * as serviceWorker from './serviceWorker';
6 |
> 7 | ReactDOM.render(<App />, document.getElementById('root'));
| ^
8 |
9 | // If you want your app to work offline and load faster, you can change
10 | // unregister() to register() below. Note this comes with some pitfalls.
最佳答案
如果 var
是 App
上的属性,那么它不是您的 props
或 state
的一部分,因此添加将其传递给 AppProps
或 AppState
接口(interface)不会让 Typescript 识别它。
相反,您实际上应该在类中定义它:
class App extends React.Component<AppProps, AppState>
{
private var: number;
constructor(props: AppProps) {
super(props);
this.var = 10;
this.state = {
};
}
render() {
return (
<div>
Hi!
</div>
)
}
}
关于javascript - 如何使用 ReactJS 和 Typescript 定义组件实例属性? `Property ' var' 在类型 'App' ` 上不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57914278/