React/Typescript : this.setState 不是函数
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
请将您的提交功能绑定到此:
this.submit = this.submit.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>
);
}
}
您需要在函数式 luke 中绑定您的方法或转换
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>
);
}
}
希望有用
我是第一次做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
请将您的提交功能绑定到此:
this.submit = this.submit.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>
);
}
}
您需要在函数式 luke 中绑定您的方法或转换
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>
);
}
}
希望有用