![](/img/trans.png)
[英]React Native w/ TypeScript this.setState is not a function
[英]React/Typescript : this.setState is not a function
我是第一次在React + Typescript中工作。
interface IState {
stateval: number;
}
class Forgotpassword extends React.Component<any, IState> {
constructor(props: any){
super(props);
this.state = { stateval: 1 };
}
public submit() {
this.setState({ stateval:2 });
}
public render() {
const { stateval} = this.state;
return (
<div className="App">
<Button onClick={this.submit}>Send OTP</Button>
</div>
);
}
}
當我單擊提交按鈕時,它會拋出
Uncaught TypeError: this.setState is not a function
無需添加構造函數方法或使用bind。 箭頭功能可以滿足您的需求。
import React, { Component } from 'react';
interface IState {
stateval: number;
}
export default class Forgotpassword extends Component<any, IState> {
state = {
stateval: 2
}
public submit = () => this.setState({ stateval: 2 });
public render() {
return (
<div className="App">
<Button onClick={this.submit}>Send OTP</Button>
</div>
);
}
}
您需要將功能綁定或方法轉換為
interface IState {
stateval: number;
}
class Forgotpassword extends React.Component<any, IState> {
constructor(props: any){
super(props);
this.state = { stateval: 1 };
}
const submit = () => {
this.setState({ stateval:2 });
}
const render = () => {
const { stateval} = this.state;
return (
<div className="App">
<Button onClick={this.submit}>Send OTP</Button>
</div>
);
}
}
我希望它有用
請將您的Submit函數綁定到此:
this.submit = this.submit.bind(this)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.