[英]Cannot access this.setState or this.state inside Ant Modal confirm ok/cancel function
I'm having issues with accessing this.state
and this.setState
inside the onCancel/onOk function.我在
this.setState
/onOk 函数中访问this.state
和this.setState
遇到问题。 I want to modify the state after confirmation or canceling the pop-up modal.我想在确认或取消弹出模态后修改状态。 If anyone's got a different approach, your guidance would be helpful.
如果有人有不同的方法,您的指导会有所帮助。
import React from 'react';
import { Button, Modal } from 'antd';
class ExampleClass extends React.Component {
constructor() {
super();
this.state = {
bankInfo: 100,
};
}
onButtonClicked() {
this.setState({ bankInfo: 200 }); // works fine
Modal.confirm({
title: 'Are you sure delete this item?',
okType: 'danger',
onOk() {
this.setState({ bankInfo: 300 }); // Uncaught TypeError: Cannot read property 'setState' of undefined
},
onCancel() {
this.setState({ bankInfo: 400 }); // Uncaught TypeError: Cannot read property 'setState' of undefined
},
});
}
render() {
return (
<div>
<Button onClick={this.onButtonClicked.bind(this)}>Click Me</Button>
</div>
);
}
}
export default ExampleClass;
I would prefer to use arrow function我更喜欢使用箭头函数
import React from 'react';
import { Button, Modal } from 'antd';
class ExampleClass extends React.Component {
constructor() {
super();
this.state = {
bankInfo: 100,
};
}
onButtonClicked = () => {
this.setState({ bankInfo: 200 });
Modal.confirm({
title: 'Are you sure delete this item?',
okType: 'danger',
onOk: () => {
this.setState({ bankInfo: 300 });
},
onCancel: () => {
this.setState({ bankInfo: 400 });
},
});
}
render() {
return (
<div>
<Button onClick={this.onButtonClicked}>Click Me</Button>
</div>
);
}
}
export default ExampleClass;
You need to bind your method to the class.您需要将您的方法绑定到类。
import React from 'react';
import { Button, Modal } from 'antd';
class ExampleClass extends React.Component {
constructor() {
super();
this.state = {
bankInfo: 100,
};
}
onOkHandler = () => {this.setState({ bankInfo: 300 })}
onCancelHandler = () => {this.setState({ bankInfo: 400 })}
onButtonClicked() {
this.setState({ bankInfo: 200 }); // works fine
Modal.confirm({
title: 'Are you sure delete this item?',
okType: 'danger',
onOk() {
this.onOkHandler()
},
onCancel() {
this.onCancelHandler()
},
});
}
render() {
return (
<div>
<Button onClick={this.onButtonClicked.bind(this)}>Click Me</Button>
</div>
);
}
}
export default ExampleClass;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.