类型“只读<{}>"上不存在属性“值" [英] Property 'value' does not exist on type 'Readonly<{}>'
问题描述
我需要创建一个表单,该表单将根据 API 的返回值显示一些内容.我正在使用以下代码:
I need to create a form that will display something based on the return value of an API. I'm working with the following code:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value); //error here
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} /> // error here
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
我收到以下错误:
error TS2339: Property 'value' does not exist on type 'Readonly<{}>'.
我在代码注释的两行中遇到了这个错误.这段代码甚至不是我的,我是从 react 官方网站 (https://reactjs.org/docs/forms.html),但它在这里不起作用.
I got this error in the two lines I commented on the code. This code isn't even mine, I got it from the react official site (https://reactjs.org/docs/forms.html), but it isn't working here.
我正在使用 create-react-app 工具.
Im using the create-react-app tool.
推荐答案
Component
定义如下:
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
表示状态(和道具)的默认类型是:{}
.
如果你想让你的组件在 state 中有 value
那么你需要像这样定义它:
Meaning that the default type for the state (and props) is: {}
.
If you want your component to have value
in the state then you need to define it like this:
class App extends React.Component<{}, { value: string }> {
...
}
或者:
type MyProps = { ... };
type MyState = { value: string };
class App extends React.Component<MyProps, MyState> {
...
}
这篇关于类型“只读<{}>"上不存在属性“值"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!