Lui*_*ann 98 typescript reactjs
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,我试图学习ReactJS,因为我需要做一个工作测试的网站,但我面临一些问题.我使用create-react-app工具,我需要创建一个表单,根据API的返回显示一些内容,但我只是在创建表单时面临问题,我在这里写的代码,我得到了以下错误:
error TS2339: Property 'value' does not exist on type 'Readonly<{}>'.
Run Code Online (Sandbox Code Playgroud)
我在代码中评论的两行中得到了这个错误.这个代码甚至不是我的,我从反应官方网站(https://reactjs.org/docs/forms.html)得到它,但它不在这里工作,我的目标是调整代码,但它不起作用,有人请帮我
Nit*_*mer 178
的Component 定义如下所示:
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
Run Code Online (Sandbox Code Playgroud)
意味着state(和props)的默认类型是:{}.
如果您希望组件value处于该状态,则需要像下面这样定义它:
class App extends React.Component<{}, { value: string }> {
...
}
Run Code Online (Sandbox Code Playgroud)
要么:
type MyProps = { ... };
type MyState = { value: string };
class App extends React.Component<MyProps, MyState> {
...
}
Run Code Online (Sandbox Code Playgroud)
Leo*_*Leo 33
除了@ nitzan-tomer的答案之外,您还可以选择使用界面:
interface MyProps {
...
}
interface MyState {
value: string
}
class App extends React.Component<MyProps, MyState> {
...
}
Run Code Online (Sandbox Code Playgroud)
只要你是一致的,要么是好的.
Sip*_*thi 18
如果你不想传递界面状态或道具模型,你可以试试这个
class App extends React.Component <any, any>
Run Code Online (Sandbox Code Playgroud)
小智 12
问题是你还没有声明你的接口状态用你合适的“值”变量类型替换任何
interface AppProps {
//code related to your props goes here
}
interface AppState {
value: any
}
class App extends React.Component<AppProps, AppState> {
// ...
}
Run Code Online (Sandbox Code Playgroud)
我建议使用
仅用于字符串状态值
export default class Home extends React.Component<{}, { [key: string]: string }> { }
Run Code Online (Sandbox Code Playgroud)
用于字符串键和任何类型的状态值
export default class Home extends React.Component<{}, { [key: string]: any}> { }
Run Code Online (Sandbox Code Playgroud)
对于任何键/任何值
export default class Home extends React.Component<{}, { [key: any]: any}> {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
65641 次 |
| 最近记录: |