无法在 Ant Modal 确认 ok/cancel 函数中访问 this.setState 或 this.state

Cannot access this.setState or this.state inside Ant Modal confirm ok/cancel function

我在 onCancel/onOk 函数中访问 this.statethis.setState 时遇到问题。我想在确认或取消弹出模态后修改状态。如果有人有不同的方法,您的指导会很有帮助。

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;

您需要将您的方法绑定到 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;

我更愿意使用箭头函数

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;