[英]React/Typescript : this.setState is not a function
I am work in react + typescript for first time. 我是第一次在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>
);
}
}
When i click the submit button it throws 当我单击提交按钮时,它会抛出
Uncaught TypeError: this.setState is not a function
There's no need to add the constructor method or use bind. 无需添加构造函数方法或使用bind。 An arrow function is fine for your needs. 箭头功能可以满足您的需求。
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>
);
}
}
you need to bind your method or trasform in functional like 您需要将功能绑定或方法转换为
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>
);
}
}
i hope it useful 我希望它有用
Please bind your submit function to this : 请将您的Submit函数绑定到此:
this.submit = this.submit.bind(this) this.submit = this.submit.bind(this)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.