Reactjs React/Typescript:this.setState不是函数
我第一次在react+typescript中工作Reactjs React/Typescript:this.setState不是函数,reactjs,typescript,setstate,Reactjs,Typescript,Setstate,我第一次在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.setS
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>
);
}
}
请将您的提交功能绑定到此:
this.submit=this.submit.bind(this)无需添加构造函数方法或使用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>
);
}
}
import React,{Component}来自'React';
界面状态{
stateval:编号;
}
导出默认类Forgotpassword扩展组件{
状态={
州:2
}
public submit=()=>this.setState({stateval:2});
公共渲染(){
返回(
发送OTP
);
}
}
您需要像函数一样绑定您的方法或Transform
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>
);
}
}
interface-IState{
stateval:编号;
}
类Forgotpassword扩展了React.Component{
构造器(道具:任何){
超级(道具);
this.state={stateval:1};
}
const submit=()=>{
this.setState({stateval:2});
}
常量渲染=()=>{
const{stateval}=this.state;
返回(
发送OTP
);
}
}
我希望它有用add
this.submit=this.submit.bind(this)
发送给构造函数。this.submit}>发送OTP
或public submit=()=>{this.setState({stateval:2});}
按钮的上下文是按钮。无论是绑定函数调用还是使用箭头函数,您都需要将提交函数绑定到上述密码类。有没有办法打印对象,因为JSON.stringify()和conssole.log()在TypeScription中不起作用尝试先打印一个简单的字符串,console.log(“Hi”)如果可以,console.log就可以了,添加规则后它必须工作“无控制台”:tslint.json文件中为false,谢谢
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>
);
}
}